认识react-redux

252 阅读1分钟

基本使用

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

  • redux+reducer=>store
//reactReduxStore.js
import { createStore } from "redux";
import { counterReducer } from "./counterReducer";

const store = createStore(counterReducer);

export default store;
  • react-redux传递store
//index.js
import React from 'react'
import ReactDom from 'react-dom'
import App from './App'
import store from './store/ReactReduxStore'
import { Provider } from 'react-redux'
ReactDom.render(
    <Provider store={store}>
        <App/>
    </Provider>,
    document.querySelector('#root')
)
  • react-redux获取store
//ReactReduxPage.js
import React, { Component } from "react";
import { connect } from "react-redux";
class ReactReduxPage extends Component {
    render() {
        const { num, add, minus, asyAdd } = this.props;
        return (
            <div>
                <h1>ReactReduxPage</h1>
                <p>{num}</p>
                <button onClick={add}>add</button>
                <button onClick={minus}>minus</button>
                {/*<button onClick={asyAdd}>asyAdd</button>*/}
            </div>
        );
    }
}

const mapStateToProps = state => ({ counter: state.counter })

const mapDispatchToProps = {
    add: () => ({ type: "add" }),
    minus: () => ({ type: "minus" }),
    //Actions must be plain objects. Use custom middleware for async actions.
    //asyAdd: () => {
    //    setTimeout(() => {
    //        return { type: "add" };
    //    }, 1000);
    //},
};

export default connect(
    mapStateToProps, //状态映射 mapStateToProps
    mapDispatchToProps, //派发事件映射
)(ReactReduxPage);

异步

//reactReduxStore.js应用中间件
import { createStore, combineReducers, applyMiddleware } from "redux";
import logger from "redux-logger";
import thunk from "redux-thunk";

import { counterReducer } from "./counterReducer";

const store = createStore(
  combineReducers({
    counter: counterReducer,
  }),
  applyMiddleware(logger, thunk),
);

export default store;
//reactReduxPage.js的变化
const mapDispatchToProps = {
    add: () => ({ type: "add" }),
    minus: () => ({ type: "minus" }),
    asyAdd: () => dispatch => {
        setTimeout(() => {
            // 异步结束后,手动执行dispatch
            dispatch({ type: "add" });
        }, 1000);
    },
};

手写版

精髓:使用useContext

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

const Context = React.createContext();

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

export function Provider({ store, children }) {
  return <Context.Provider value={store}>{children}</Context.Provider>;
}

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 <Cmp {...props} {...moreProps} />;
};