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
}
}
}
这里参数为什么要用展开符? 使用的时候传入的是数组,如:
const middlewares = [ thunk, logger ]
applyMiddleware(...middlewares)
那这样函数中 middlewares.map 的 middlewares岂不是 [[thunk, logger]]了么。
PS: 奥。。明白了,同时支持applyMiddleware(thunk, logger)和applyMiddleware(...[thunk, logger])两种方式调用。
大家忽略吧
倚天杖
相关分类