react-redux学习

122 阅读1分钟

react-redux的作用

1、避免redux中store全局化,把store直接继承到react应用的顶层props里面,方便各个子组件能访问到顶层props

2、解决手动监听state中的数据变化

react-redux中的几个核心知识点

  1. connect:用于从 UI 组件生成容器组件,从而将这两种组件连起来;

  2. mapStateToProps:建立一个从(外部的)state对象到(UI 组件的)props对象的映射关系;

  3. mapDispatchToProps:建立 UI 组件的参数到store.dispatch方法的映射;

  4. Provider:Provider在根组件外面包了一层,这样App中的所有子组件就默认都可以拿到state;

provider

<Provider store={store}>
  <App />
</Provider>

在根组件外面包了一层,将store传进去

connect

connect(mapStateToProps,mapDispatchToProps)(MyComponent)

用于从 UI 组件生成容器组件,从而将这两种组件连起来;

mapStateToProps

const mapStateToProps = (state) => {
    return {
        count: state
    }
}

渲染:this.props.todos 目的:把Redux中的state变成React中的props

mapDispatchToProps

把各种dispatch也变成了props,在组件中可以直接使用

避免了手动去用store.subscribe订阅render函数以达到更新页面的作用的目的

案例

const mapDispatchToProps = (dispatch) => {
  return {
    handleAdd: () => {
      dispatch({ type: "ADD" })
    }
  };
}

案例

import React, { Component } from "react";
import { connect } from "react-redux";

class ReactReduxPage extends Component {
  render() {
    const { count, handleAdd } = this.props;
    return (
      <div>
        <h3>ReactReduxPage</h3>
        <p>{count}</p>
        <button onClick={() => handleAdd()}>add</button>
      </div>
    );
  }
}

// 把 redux 中的 state 变成 react 中的 props
const mapStateToProps = (state) => {
  return {
    count: state
  };
}

// 把各种 dispatch 也变成了 props ,在组件中可以直接使用
const mapDispatchToProps = (dispatch) => {
  return {
    handleAdd: () => {
      dispatch({ type: "ADD" })
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(ReactReduxPage);