简体   繁体   English

React Redux中间件的流程如何工作?

[英]how does the flow of a react redux middleware work?

Where does thunk middleware come into place? 笨拙的中间件在哪里出现? This is the order of the middlewares that I see this going through right now but I get stuck on where Thunk comes in: 这是我现在看到的中间件的顺序,但是我陷入了Thunk进入的位置:

  1. dispatches action that has promise value set to true 调度将promise值设置为true的操作
  2. goes to thunk, thunk doesn't do anything with it because it's an object, not function 变得笨拙,笨拙不做任何事情,因为它是一个对象,而不是函数
  3. goes to promiseErrorMiddleware, which gets store from applyMiddlware and returns a function. 转到promiseErrorMiddleware,它从applyMiddlware获取存储并返回一个函数。
  4. does this function get intercepted by Thunk even though it was returned, and not dispatched? Thunk是否已返回但未调度该函数,但该函数是否被Thunk拦截? who exactly runs this function that will return the next function with the action as an argument? 谁确切地运行此函数,该函数将以该操作作为参数返回下一个函数? who will then run that final function? 谁来运行最终功能?

Store 商店

const store = createStore(
  rootReducer,
  applyMiddleware(thunkMiddleware, promiseErrorMiddleware, dataTrafficMiddleware)
)

actionCreator actionCreator

dispatch({url: requestURL, promise: true})

promiseErrorMiddleware & dataTrafficMiddleware promiseErrorMiddleware和dataTrafficMiddleware

const promiseErrorMiddleware = function (store) { //where is store from, applyMiddleware?
      return function (next) { //where is next from?
        return function (action) {
          if (!action.promise) {
            return next(action)
          } else {
            return fetch(action.url).then(function (data) {
              ...
              next({data, needDirection: true})
            })
          }
        }
      }
    }

const dataTrafficMiddleware = function (store) {
  return function (next) {
    return function (action) {
      if (!action.needDirection) {
        return next(action)
      } else {
        //dispatch regular action with type and data
      }
      }
    }
  }
}

One thing to keep in mind is that the middlewares are chained. 要记住的一件事是中间件是链接在一起的。 When you call next() it goes to the next middleware, in the order you defined them in applyMiddleware() . 当您调用next()它将按照您在applyMiddleware()定义它们的顺序转到下一个中​​间件。 At the end of the middleware chain the action goes through the reducer(s). 在中间件链的末尾,操作通过化简器进行。 In your code, the function is never getting passed through the thunk middleware (since thunk comes before promiseErrorMiddleware ). 在您的代码中,该函数永远不会通过thunk中间件传递(因为thunkpromiseErrorMiddleware之前)。 On the other hand, if you dispatch() the action, it will run through the entire middleware chain from the beginning. 另一方面,如果您dispatch()操作,则该操作将从头开始贯穿整个中间件链。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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