有了redux相关组件,也不能达到完全准确定位bug的一个目的,这时候就需要日志来记录我们的action操作。
有一点原则需要注意,写中间件的时候,尽量或者说一定要写成纯函数(return新东西),尽可能地少对传入的参数做直接修改。
完整测试代码如下:
import store from './store/index.js';
import {
addAction,
subAction
} from './store/actionCreators.js'
store.subscribe(() => {
// console.log(store.getState());
})
// 1.基本做法
// console.log('dispatch前 --- dispatching action:', addAction(10));
// store.dispatch(addAction(10));
// console.log('dispatch后 --- dispatching action:', store.getState());
// store.dispatch(addAction(15));
// 2. 封装一个函数
// function dispatchAndLogging(action) {
// console.log('dispatch前 --- dispatching action:', action);
// store.dispatch(addAction(10));
// console.log('dispatch后 --- dispatching action:', store.getState());
// }
// dispatchAndLogging(addAction(10));
// dispatchAndLogging(addAction(5));
// 3. 函数基础之上进行优化:修改原有dispatch
// hack技术:monkeying patch 修改原有API中代码逻辑
// const next = store.dispatch;
// function dispatchAndLogging(action) {
// console.log('dispatch前 --- dispatching action:', action);
// next(action);
// console.log('dispatch后 --- dispatching action:', store.getState());
// }
// store.dispatch = dispatchAndLogging;
// store.dispatch(addAction(10));
// store.dispatch(addAction(5));
// 4. 对之前的操作进行封装
// 相当于高阶函数 / 装饰器模式,每次都会添加新功能
function patchLogging(store) {
const next = store.dispatch;
function dispatchAndLogging(action) {
console.log('dispatch前 --- dispatching action:', action);
next(action);
console.log('dispatch后 --- dispatching action:', store.getState());
}
// store.dispatch = dispatchAndLogging;
// 也可以返回自定义
return dispatchAndLogging;
}
// 封装patchThunk的功能
function patchThunk(store) {
const next = store.dispatch;
function dispatchAndThunk(action){
if(typeof action === "function"){
// 传入函数则执行函数
action(store.dispatch, store.getState);
} else {
// 不为函数则直接next()
next(action);
}
}
// store.dispatch = dispatchAndThunk;
// 也可以返回自定义thunk,达到纯函数目的
return dispatchAndThunk;
}
patchLogging(store);
patchThunk(store);
// function foo(dispatch, getState){
// dispatch(subAction(10));
// }
// store.dispatch(foo);
// store.dispatch(subAction(1));
// store.dispatch(addAction(10));
// store.dispatch(addAction(5));
// 5. 封装applyMiddleware,当前写法不是纯函数。
function applyMiddleware(store, ...middlewares) {
// 开发中做浅拷贝
// const newMiddleware = [...middlewares];
middlewares.forEach(middleware => {
store.dispatch = middleware(store);
})
}
applyMiddleware(store, patchLogging, patchThunk);