我的问题是为什么middlewareAPI
无法使用:
const middlewareAPI = {
getState: store.getState,
dispatch: dispatch
}
替换源代码中的定义如下:
export default function applyMiddleware(...middlewares) {
return (createStore) => (reducer, preloadedState, enhancer) => {
const store = createStore(reducer, preloadedState, enhancer)
let dispatch = store.dispatch
let chain = []
const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args) // why not just use `dispatch: dispatch`
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
任何人都可以告诉我区别吗?感谢。
答案 0 :(得分:1)
这是一个有点复杂的JS变量范围/托管组合,需要确保传入的调度方法实际上指向中间件链的开始。
有关详细信息,请参阅新添加的(尚未发布的)Redux FAQ entry on why applyMiddleware
uses a closure。