How does this example from shrinking documentation work?

I read the Redux documentation and lists various ways to use middleware that may work but are not effective before it gets to how Redux really uses middleware.

I have no idea why this next method worked, although I can 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])
Run codeHide result

How could this work? Aren't you just rewriting the store.dispatch () function with each iteration of the forEach loop, and in the end all you use is the last middleware in the array?

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

+4
2

, .

, , . .

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

store.dispatch = logger(store)

, store logger. logger next store.dispatch. , . next(action) result result.

, store.dispatch, , , .

? , , : ( ) store.dispatch

+1

.

0

Source: https://habr.com/ru/post/1684182/


All Articles