【问题标题】:Dispatching an action from middleware results in a strange behavior从中间件分派动作会导致奇怪的行为
【发布时间】:2020-06-17 17:04:01
【问题描述】:

这里是 Redux 新手。我了解动作、中间件和化简器的核心概念,但其中一个代码 sn-ps 的工作方式与我预期的不同。我不认为这是一个错误,但我想知道为什么事情会以这种方式发生。

所以,这里有一个代码:

const middlewareOne = store => next => action => {
        console.log('Middleware one recived action', action.type)
        switch (action.type) {
          case 'A':
            return next({ type: 'B' })
          default:
            return next(action)
        }
      }

      const middlewareTwo = store => next => action => {
        console.log('Middleware two recived action', action.type)
        switch (action.type) {
            case 'B':
                store.dispatch({ type: 'D' })
                return next({ type: 'C' })
            default:
                return next(action)
        }
      }

      function reducer(state, action)
        console.log('Reducer received action', action.type)
            return state
      }

我有动作 A、B、C 和 D、两个中间件和 reducer。 第一个中间件通过调用 next() 函数接收动作 A 并产生动作 B。

第二个中间件接收动作 B 并产生动作 C,并分派动作 D。

据我了解,从中间件调度操作没有任何问题,但结果让我非常惊讶。

这是此代码的控制台输出

Middleware one receive action A 
Middleware two receive action B 
Middleware one receive action D 
Middleware two receive action D 
Reducer received action D 
Reducer received action C

所以,我除了: 据我所知,如果链中没有中间件,next() 函数会将操作传递给下一个中间件或减速器,但 dispatch 会将操作放在管道的开头(所有中间件,最后是减速器)。所以,考虑到这个想法,我认为首先会减少动作 C(因为它已经在中间件管道中),并且只有在中间件开始处理动作 D 之后,但结果完全相反。你能解释一下为什么会这样吗?

最好的问候,维塔利·苏利莫夫。

【问题讨论】:

    标签: redux


    【解决方案1】:

    我对 redux 也比较陌生,按照我的理解,这些调用不是异步的,所以它们是按顺序执行的。您首先调度 D,这样在调用 Next 之前,它将遍历整个中间件和 reducer 链。

    所以您的 return next({ type: 'C' }) 调用仅在 store.dispatch({ type: 'D' }) 完成处理后发生

    【讨论】:

    • 是的,你是对的。那是我超级愚蠢的错误。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    相关资源
    最近更新 更多