redux中applyMiddleware源码,中文注释

理解applyMiddleware须要跟createStore结合.首先来看createStore是怎样建立store的.express

clipboard.png
再来看createStore 的源码redux

clipboard.png

createStore的第三个参数enhancer就是applyMiddleware,此时createStore会返回enhancer(createStore)(reducer, preloadedState),也就是createStore在中间件里面去执行了app

applyMiddleware返回的是函数A(也就是applyMiddleware(...middlewares) =函数A,而后又跑到createStore里面做为第三个参数),因此能把createStore做为参数传进去异步

clipboard.png

一个小例子,测试返回函数后是什么东西async

clipboard.png

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
    }
  }
}
相关文章
相关标签/搜索