React foundation consolidation (38) - the core code of log, thunk, applyMiddleware middleware
1. Print log - middleware core code
Use Monkey Patching to modify the original program logic, and realize the log printing function through dispatchAndLog in the process of calling dispatch
// 打印日志-中间件核心代码
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;
Two, thunk-middleware core code
The use of middleware in redux redux-thunk
allows dispatch not only to process objects, but also to process functions
// 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;
3. applyMiddleware- middleware core code
It is very inconvenient to call a single function to apply middleware. Encapsulate a function to combine middleware
function applyMiddleware(store, ...fns) {
fns.forEach(fn => {
fn(store)
})
}
export default applyMiddleware
4. Application middleware
Apply the above three manually encapsulated middleware in store/index.js:
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;