简体   繁体   English

在Redux中间件中调度多个动作

[英]Dispatch multiple action in redux middleware

I have this React Native app along with redux where all HTTP requests are performed through async actions using redux-promise-middleware . 我有这个React Native应用程序以及redux,其中所有HTTP请求都是通过使用redux-promise-middleware通过异步操作执行的。

Now I want to handle every error that can be sent by the API and for that I'm implementing a redux middleware that will intercept every action with the type XXX_REJECTED (since redux-promise-middleware dispatches a _REJECTED action when an async action fails). 现在,我想处理API可能发送的每个错误,为此,我正在实现一个Redux中间件,该中间件将拦截类型为XXX_REJECTED每个操作(因为redux-promise-middleware在异步操作失败时会调度_REJECTED操作) 。

But now I have this problem... In the middleware I want to be able to dispatch a new action (a API_ERROR for instance) and still be able to perform next() for the original action (the XXX_REJECTED ). 但是现在我有这个问题...在中间件中,我希望能够调度一个新动作(例如API_ERROR ),并且仍然能够对原始动作( XXX_REJECTED )执行next() )。

Here's my middleware: 这是我的中间件:

export default ({ dispatch }) => next => (action) => {
  if (action.type.match(/w*(_REJECTED)/)) {
    dispatch({
      type: 'API_ERROR',
      payload: action.payload,
    })
  }

  next(action)
}

But with this code once the new action is dispatched, the next() is never executed. 但是使用此代码,一旦分派了新操作,就永远不会执行next()

Does this make sense? 这有意义吗? Is it possible to dispatch multiple actions in a middleware? 是否可以在中间件中调度多个动作?

I think you need to return the next action. 我认为您需要返回下一个动作。 And yes you should be able to dispatch as many actions as you want. 是的,您应该能够调度任意数量的操作。

return next(action)

Found that everything was ok with the middleware. 发现中间件一切正常。 You can dispatch as many actions as you wish. 您可以根据需要调度任意多个动作。

My mistake was in the reducer, where I had a case with no state returned from it (only a console.log(action) ). 我的错误是在化简器中,那里有一个没有返回状态的case (仅console.log(action) )。

My bad! 我的错!

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

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