gpt4 book ai didi

redux - 从中间件分派(dispatch) Action 会导致奇怪的行为

转载 作者:行者123 更新时间:2023-12-04 13:55:55 25 4
gpt4 key购买 nike

Redux 新手在这里。我了解操作、中间件和化简器的核心概念,但其中一个代码片段的工作方式与我预期的不一样。我不认为这是一个错误,但我想知道为什么会这样。

所以,这是一个代码:

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
}

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

第二个中间件接收 Action B 并产生 Action C,然后分派(dispatch) Action D。

据我所知,从中间件分派(dispatch) Action 并没有错,但结果让我非常惊讶。

这是此代码的控制台输出
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() 函数将 Action 传递给下一个中间件或 reducer ,但 dispatch 将 Action 放在管道的开头(所有中间件,最后是 reducer )。所以,考虑到这个想法,我认为首先会减少 Action C(因为它已经在中间件管道中),只有在中间件开始处理 Action D之后,结果才完全相反。你能解释一下为什么会发生这种情况吗?

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

最佳答案

我对 redux 也比较陌生,按照我的理解,这些调用不是异步的,所以它们是按顺序执行的。你首先调度 D,这样它就会在调用 Next 之前通过整个中间件和 reducer 链。
所以你的 return next({ type: 'C' }) 调用只在 store.dispatch({ type: 'D' }) 完成处理后发生

关于redux - 从中间件分派(dispatch) Action 会导致奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62434483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com