React 基礎(chǔ)鞏固(三十八)——log、thunk、applyMiddleware中間件的核心代碼
一、打印日志-中間件核心代碼
利用Monkey Patching,修改原有的程序邏輯,在調(diào)用dispatch的過程中,通過dispatchAndLog實(shí)現(xiàn)日志打印功能
// 打印日志-中間件核心代碼
function log(store) {
const next = store.dispatch;
function logAndDispatch(action) {
console.log("當(dāng)前派發(fā)的action:", action);
// 真正派發(fā)的代碼:使用之前的dispatch進(jìn)行派發(fā)
next(action);
console.log("派發(fā)之后的結(jié)果:", store.getState());
}
// monkey patch: 猴補(bǔ)丁 => 篡改現(xiàn)有的代碼,對(duì)整體的執(zhí)行邏輯進(jìn)行修改
store.dispatch = logAndDispatch;
}
export default log;
二、thunk-中間件核心代碼
redux中利用中間件redux-thunk
可以讓dispatch不不僅能處理對(duì)象,還能處理函數(shù)
// 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-中間件核心代碼
單個(gè)調(diào)用函數(shù)來應(yīng)用中間件,非常不方便,封裝一個(gè)函數(shù)來合并中間件文章來源:http://www.zghlxwxcb.cn/news/detail-621310.html
function applyMiddleware(store, ...fns) {
fns.forEach(fn => {
fn(store)
})
}
export default applyMiddleware
四、應(yīng)用中間件
在store/index.js中應(yīng)用上面三個(gè)手動(dòng)封裝的中間件:文章來源地址http://www.zghlxwxcb.cn/news/detail-621310.html
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,
},
});
// 應(yīng)用中間件
applyMiddleware(store, log, thunk);
export default store;
到了這里,關(guān)于【前端知識(shí)】React 基礎(chǔ)鞏固(三十八)——log、thunk、applyMiddleware中間件的核心代碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!