Redux

核心组件

定义 Action

Reducer 的作用

为什么 reducer 中不能做异步操作(为什么是纯函数)

React-Redux

异步 Action 方案

源码实现

connect 实现

const connect = (mapStatetoProps, mapActionstoProps) => (WrapperComponent) => {
  return class Connect extends Component {
    static contextType = storeContext; // provide 定义的 context 对象

    constructor(props) {
      super();
    }

    componentWillMount() {
      const store = this.context;
      store.subscribe(this._updateProps);
      this._updateProps(); // 初始化
    }

    _updateProps = () => {
      const store = this.context;
      // 传入state和props
      const stateProps = mapStatetoProps ? mapStatetoProps(store.getState(), this.props) : {};
      // 传入dispatch和props
      const actionProps = mapActionstoProps ? mapActionstoProps(store.dispatch, this.props) : {};
      //整合props,传给接收的组件
      this.setState({
        allProps: {
          ...stateProps,
          ...actionProps,
          ...this.props,
        },
      });
    };

    render() {
      return <WrapperComponent {...this.state.allProps} />;
    }
  };
};