模仿react-redux源码实现

原理:

index.js 用Provider标签包裹,并传入store实例
MyReactReduxPage:从props结构出属性和方法,在页面实现,导入connect高阶函数
counterReducer: 传入state和action 返回新的state
MyReactReduxStore:导入redux的createStore,创建store实例传入counterReducer。
kReactRedux.js:

src/pages/MyReactReduxPage.js

import React, { Component } from "react";
import { connect } from "../kReactRedux";

class MyReactReduxPage extends Component {
  render() {
    console.log("props", this.props);
    const { counter, add, minus } = this.props;
    return (
      

MyReactReduxPage

{counter}

); } } export default connect( //mapStateToProps state => ({ counter: state }), //mapDispatchToProps { add: () => ({ type: "add" }), minus: () => ({ type: "minus" }), }, )(MyReactReduxPage);

src/store/MyReactReduxStore.js

import { createStore } from "redux";

import { counterReducer } from "./counterReducer";

const store = createStore(counterReducer);

export default store;

src/store/counterReducer.js

export function counterReducer(state = 0, action) {
  switch (action.type) {
    case "add":
      return state + 1;
    case "minus":
      return state - 1;
    default:
      return state;
  }
}

src/kReactRedux.js

import React, { useState, useContext, useEffect } from "react";
// import { bindActionCreators } from "redux";

const Context = React.createContext();

export function Provider({ store, children }) {
  return {children};
}

export const connect = (
  mapStateToProps = state => state,
  mapDispatchToProps = {},
) => Cmp => props => {
  const store = useContext(Context);
  const getMoreProps = () => {
    const stateProps = mapStateToProps(store.getState());
    const dispatchProps = bindActionCreators(
      mapDispatchToProps,
      store.dispatch,
    );
    return {
      ...stateProps,
      ...dispatchProps,
    };
  };
  useEffect(() => {
    store.subscribe(() => {
      setMoreProps({ ...moreProps, ...getMoreProps() });
    });
  }, []);
  const [moreProps, setMoreProps] = useState(getMoreProps());
  return ;
};

function bindActionCreator(creator, dispatch) {
  return (...args) => dispatch(creator(...args));
}
//{add: ()=>({type:'add'}), minus: ()=>({type: 'minus})
function bindActionCreators(actionCreators, dispatch) {
  let obj = {};
  for (let key in actionCreators) {
    obj[key] = bindActionCreator(actionCreators[key], dispatch);
  }
  return obj;
}

你可能感兴趣的:(模仿react-redux源码实现)