Redux - applyMiddleware源码解析

applyMiddleware 干啥,就是创建了一个新的createStore方法,这个新的方法里 会执行你带入的function

export default function applyMiddleware(...middlewares) {
return (createStore) => (reducer, initialState, enhancer) => {
var store = createStore(reducer, initialState, enhancer)
var dispatch = store.dispatch
var chain = []

var middlewareAPI = {
getState: store.getState,
dispatch: (action) => dispatch(action)
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)

return {
...store,
dispatch
}
}
}

你带入function的数组和createStore

得到的是一个 新的function

(reducer, initialState, enhancer) => {
var store = createStore(reducer, initialState, enhancer)
var dispatch = store.dispatch
var chain = []

var middlewareAPI = {
getState: store.getState,
dispatch: (action) => dispatch(action)
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)

return {
...store,
dispatch
}
}

这个新的有什么特别呢:

  • 他替换了一个新的dispatch
    • 这个你出入的每个function对 原来store的 getState 和dispatch进行处理(是不是想起了Connect?),相当于给你一个机会自己造dispatch
    • dispatch = compose(...chain)(store.dispatch)这个的意思是,你早了你自己的dispatch,但你里面的根本还是要调用store.dispatch