Redux 从中间件分派操作会导致奇怪的行为
这里是Redux新手。我理解actions、中间件和Reducer的核心概念,但其中一个代码片段的工作方式与我预期的不同。我不认为这是一个错误,但我想知道为什么事情会以这种方式发生 下面是一个代码:Redux 从中间件分派操作会导致奇怪的行为,redux,Redux,这里是Redux新手。我理解actions、中间件和Reducer的核心概念,但其中一个代码片段的工作方式与我预期的不同。我不认为这是一个错误,但我想知道为什么事情会以这种方式发生 下面是一个代码: const middlewareOne = store => next => action => { console.log('Middleware one recived action', action.type) switch (action.t
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,两个中间件和减速机。
第一个中间件接收动作A,并通过调用next()函数生成动作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()函数将操作传递给下一个中间件,如果链中没有中间件,则传递给reducer,但dispatch将操作传递到管道的开头(所有中间件,最后是reducer)。因此,考虑到这个想法,我认为动作C首先会减少(因为它已经在中间件管道中),只有在中间件开始处理动作D之后,结果完全相反。你能解释一下为什么会这样吗
最好的问候,Vitaly Sulimov。我对redux也比较陌生,据我所知,这些调用不是异步的,所以它们是按顺序执行的。您首先调度D,这样在调用Next之前,它将遍历整个中间产品链和减速机链
因此,您的下一个返回({type:'C'})调用只在store.dispatch({type:'D'})完成处理后发生是的,您是对的。那是我的超级愚蠢的错误。谢谢