中间件本质就是得到一个新的dispatch创建函数,调用创建函数,重写了store.dispatch(action),依次执行新的dispatch(action)方法,来改变store中的state
我们从一个小案例来说明中间件函数的由来:
//由action创建函数addTodo创建一个action对象
const action = addTodo('Use Redux')
//打印action对象
console.log('dispatching', action)
store.dispatch(action)
//打印下一个状态
console.log('next state', store.getState())
这是我们想要的效果,但不想每次都这样做手动创建,我们希望用一个函数来自动创建
将日志记录提取到函数中:
function dispatch(store, action) { console.log('dispatching', action) store.dispatch(action) console.log('next state', store.getState()) }
'运行
然后,在任何地方使用它,而不是store.dispatch():
dispatch(store, addTodo('Use Redux'))
我们可以到这里结束,但是每次都导入一个特殊的函数不是很方便。
Monkeypatching 是一种黑客攻击。“替换任何你喜欢的方法”
const next = store.dispatch //保存源dispatch
//重写dispatch
store.dispatch = function dispatch(action) {
console.log('dispatching', action)
let result = next(action) //调用原始的dispatch方法
console.log('next state', store.getState(