The implementation of Redux's applyMiddleware

573 Views Asked by At

My question is why middlewareAPI can't use :

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

to replace the definition in the source code as below:

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
    }
  }
}

Anyone can tell me the difference ? Thanks.

1

There are 1 best solutions below

0
On BEST ANSWER

It's a somewhat complicated combination of JS variable scoping/hosting, and needing to ensure that the passed-in dispatch method actually points back to the start of the middleware chain.

Please see the newly-added (and not yet published) Redux FAQ entry on why applyMiddleware uses a closure for more details.