Redux的applyMiddleware的实现

时间:2017-09-06 08:41:26

标签: redux redux-middleware

我的问题是为什么middlewareAPI无法使用:

const middlewareAPI = {
  getState: store.getState,
  dispatch: dispatch
}

替换源代码中的定义如下:

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: (...args) => dispatch(...args)   // why not just use `dispatch: dispatch`
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}

任何人都可以告诉我区别吗?感谢。

1 个答案:

答案 0 :(得分:1)

这是一个有点复杂的JS变量范围/托管组合,需要确保传入的调度方法实际上指向中间件链的开始。

有关详细信息,请参阅新添加的(尚未发布的)Redux FAQ entry on why applyMiddleware uses a closure