React 基础巩固(三十八)------log、thunk、applyMiddleware中间件的核心代码
一、打印日志-中间件核心代码
利用Monkey Patching,修改原有的程序逻辑,在调用dispatch的过程中,通过dispatchAndLog实现日志打印功能
javascript
// 打印日志-中间件核心代码
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;
二、thunk-中间件核心代码
redux中利用中间件redux-thunk
可以让dispatch不不仅能处理对象,还能处理函数
javascript
// react-thunk-中间件核心代码
function thunk(store) {
const next = store.dispatch;
function dispatchThunk(action) {
if (typeof action === "function") {
action(store.dispatch.store.getState);
} else {
next(action);
}
}
store.dispatch = dispatchThunk;
}
export default thunk;
三、applyMiddleware-中间件核心代码
单个调用函数来应用中间件,非常不方便,封装一个函数来合并中间件
javascript
function applyMiddleware(store, ...fns) {
fns.forEach(fn => {
fn(store)
})
}
export default applyMiddleware
四、应用中间件
在store/index.js中应用上面三个手动封装的中间件:
javascript
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./features/counter";
import homeReducer from "./features/home";
// 引入中间件
import { log, thunk, applyMiddleware } from "./middleware";
const store = configureStore({
reducer: {
counter: counterReducer,
home: homeReducer,
},
});
// 应用中间件
applyMiddleware(store, log, thunk);
export default store;