还是先直接上代码
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: (action) => dispatch(action)
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
再来看看我们用到的地方,在我们createStore时
return enhancer(createStore)(reducer, preloadedState)
再来看看我们的业务代码中怎么使用的
const store = createStore(rootReducer, initialState, compose(
applyMiddleware(...middlewares),
devToolsExtension
))
有几点要说明下
- createStore时,增强器是为了丰富dispatch功能的
- compose是为了叠加执行方法的,由上一篇我们知道,就是传入一个值,然后对这个值进行丰富
综上所述,applyMiddleWare就是为了丰富dispatch的
- compose是为了叠加执行方法的,由上一篇我们知道,就是传入一个值,然后对这个值进行丰富
网友评论