Middleware
中间件又回归了老式的声明action的形式,这是因为在middleware中,声明式的action更方便展示和判断
middleware的格式
({ getState }) => next => async action => {
// do something
await next()
// do something
},
// getState: 和useStoreState的使用方式一样,也是传入"访问路径"获取当前的状态
// next: 进入下一步,有可能是middleware,也有可能执行到了effect或reducer
注意,next执行时一定要用await命令
在dispatc是h的扩展的设计图中可以看到,middleware是层层包在外边的,这就形成了koa的middleware形式
例如
const middlewares = [
({ getState }) => next => async action => {
console.log('m1 start')
await next()
console.log('m1 end')
},
({ getState }) => next => async action => {
console.log('m2 start')
await next()
console.log('m2 end')
},
]
// 最终每次执行dispatch时,都会输出如下
// 'm1 start'
// 'm2 start'
// 'm2 end'
// 'm1 end'
由于getState方法是实时的,所以即便是在同一个middleware内,getState在next执行的前后也有可能不一样
({ getState }) => next => async action => {
const team1 = getState(['team'])
await next() // 假装这里有修改team的操作
const team2 = getState(['team'])
console.log(team1 === team2) // false
}
Last updated
Was this helpful?