【发布时间】: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