共计 1555 个字符,预计需要花费 4 分钟才能阅读完成。
理解 applyMiddleware 需要跟 createStore 结合. 首先来看 createStore 是怎样创建 store 的.
再来看 createStore 的源码
createStore 的第三个参数 enhancer 就是 applyMiddleware, 此时 createStore 会返回 enhancer(createStore)(reducer, preloadedState), 也就是 createStore 在中间件里面去执行了
applyMiddleware 返回的是函数 A(也就是 applyMiddleware(…middlewares) = 函数 A, 然后又跑到 createStore 里面作为第三个参数 ), 所以能把 createStore 作为参数传进去
一个小例子, 测试返回函数后是什么东西
import compose from ‘./compose’
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* 创建一个 redux store 的 dispatch 方法使用中间件的 store 增强器. 对于不同的人任务, 这将会
* 非常方便, 比如可以用非常简单的方式进行异步操作, 或者输出 action 的 payload
*
* See `redux-thunk` package as an example of the Redux middleware.
* 查看 `redux-thunk` 包作为一个 redux 中间件的例子
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* 因为中间件默认是异步的, 这应该是合成链中的第一个 store 增强器
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
* 注意每个中间件都会以 `dispatch` and `getState` 方法作为参数
* @param {…Function} middlewares The middleware chain to be applied. 提供的中间件
* @returns {Function} A store enhancer applying the middleware.store 增强器应用的中间件
*/
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
}
}
}