React18中间件实现,redux-thunk,applyMiddleware,React中的state如何管理

124 阅读1分钟

中间件实现

monkey patch

image.png

自己实现redux-thunk,applyMiddleware

image.png

// import { createStore, applyMiddleware, compose, combineReducers } from "redux";
import { createStore, combineReducers } from "redux";
// import thunk from "redux-thunk";
// import reducer from "./reducer";
import countReducer from "./count";
import homeReducer from "./home";
import userReducer from "./user";
import { applyMiddleware, log, thunk } from "./middleware";

// 自定义中间件

// 将两个reducer合并在一起
const reducer = combineReducers({
  count: countReducer,
  home: homeReducer,
  user: userReducer,
});

// const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ trace: true }) || compose;

// 正常情况下 store.dispatch(object)
// 想派发函数 store.dispatch(function)使用中间件

// const store = createStore(reducer, composeEnhancers(applyMiddleware(thunk)));
const store = createStore(reducer);
applyMiddleware(store, log, thunk);
export default store;
function applyMiddleware(store, ...fns) {
  fns.forEach((fn) => {
    fn(store);
  });
}
export default applyMiddleware;
import thunk from "./thunk";
import log from "./log";
import applyMiddleware from "./applyMiddleware";
export { thunk, log, applyMiddleware };
// 对每次派发的action进行拦截,进行日志打印
function log(store) {
  const next = store.dispatch;
  function logAndDispatch(action) {
    console.log("当前派发的action:", action);
    // 真正派发的代码:使用之前的dispatch进行派发
    next(action);
    console.log("派发之后的结果:", store.getState());
  }
  // monkey patch:猴补丁 => 篡改现有的代码,对整体的执行逻辑进行修改
  store.dispatch = logAndDispatch;
}
export default log;
function thunk(store) {
  // 第一次的store
  const next = store.dispatch;
  function dispatchThunk(action) {
    if (typeof action === "function") {
      // action是函数,立即执行这个函数,传入两个参数
      // 参数一:上一次的dispatch,参数二:state
      action(store.dispatch, store.getState);
    } else {
      next(action);
    }
  }
  store.dispatch = dispatchThunk;
}
export default thunk;

image.png

React中的state如何管理

image.png

image.png