简体   繁体   中英

How does this example from the redux documentation work?

I am reading the Redux documentation and it lists different ways of applying middleware that could work, but are not efficient before it gets to how Redux actually applies middleware.

I have no idea why this following method would work even though I see why it is not efficient:

 function applyMiddlewareByMonkeypatching(store, middlewares) { middlewares = middlewares.slice() middlewares.reverse() // Transform dispatch function with each middleware. middlewares.forEach(middleware => store.dispatch = middleware(store) ) } // We could use it to apply multiple middleware like this: applyMiddlewareByMonkeypatching(store, [logger, crashReporter]) 

How could that possibly work? Wouldn't you just be overwriting the store.dispatch() function with every iteration of the forEach loop, and in the end all you would be applying is the last middleware in the array?

Here is a link to the documentation: http://redux.js.org/docs/advanced/Middleware.html

After going through the docs, I believe I have an answer for you.

Let's take the logger function for example. Here it is below.

function logger(store) {
  let next = store.dispatch

  // Previously:
  // store.dispatch = function dispatchAndLog(action) {

  return function dispatchAndLog(action) {
    console.log('dispatching', action)
    let result = next(action)
    console.log('next state', store.getState())
    return result
  }
}

Here is the call to the logger function below

store.dispatch = logger(store)

So the store instance gets passed to logger . Once inside the logger function, the next variable holds the reference to the original store.dispatch function. Notice it has not been overwritten yet. Now, you dispatch the action using this line next(action) and store that in result and return the result value.

The whole reason you are overwriting the store.dispatch function is so that you don't have to make an explicit call to any middleware you are trying to apply.

From the docs

Why do we even overwrite dispatch? Of course, to be able to call it later, but there's also another reason: so that every middleware can access (and call) the previously wrapped store.dispatch

It is by the magic of closures.

Original Dispatch function in stored in next variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM