【问题标题】:how does the flow of a react redux middleware work?react redux 中间件的流程是如何工作的?
【发布时间】:2017-02-08 11:20:02
【问题描述】:

thunk 中间件在哪里出现?这是我现在看到的中间件的顺序,但我卡在 Thunk 的来源上:

  1. 调度将 promise 值设置为 true 的操作
  2. 进入 thunk,thunk 对它没有任何作用,因为它是一个对象,而不是函数
  3. 转到promiseErrorMiddleware,它从applyMiddlware 获取存储并返回一个函数。
  4. 此函数是否会被 Thunk 截获,即使它已返回且未分派?究竟是谁运行了这个函数,它将返回下一个函数,并将动作作为参数?然后谁来运行最后的函数?

商店

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

actionCreator

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

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

【问题讨论】:

标签: javascript reactjs redux react-redux redux-thunk


【解决方案1】:

要记住的一件事是中间件是链式的。当您调用next() 时,它会按照您在applyMiddleware() 中定义的顺序转到下一个中​​间件。在中间件链的末端,动作通过 reducer。在您的代码中,该函数永远不会通过thunk 中间件传递(因为thunk 位于promiseErrorMiddleware 之前)。另一方面,如果你dispatch()这个动作,它会从一开始就贯穿整个中间件链。

【讨论】:

    猜你喜欢
    • 2016-09-16
    • 2020-07-18
    • 1970-01-01
    • 2017-01-24
    • 2018-06-30
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多