中间件实现
monkey patch

自己实现redux-thunk,applyMiddleware

import { createStore, combineReducers } from "redux";
import countReducer from "./count";
import homeReducer from "./home";
import userReducer from "./user";
import { applyMiddleware, log, thunk } from "./middleware";
const reducer = combineReducers({
count: countReducer,
home: homeReducer,
user: userReducer,
});
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 };
function log(store) {
const next = store.dispatch;
function logAndDispatch(action) {
console.log("当前派发的action:", action);
next(action);
console.log("派发之后的结果:", store.getState());
}
store.dispatch = logAndDispatch;
}
export default log;
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;

React中的state如何管理

