创建一个Redux Reducer,它在调用所有其他Reducer时自动运行

cbeh67ev  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(178)

我有一个createSnapshot reducer,它将在状态发生变化时存储切片的一部分的快照。我有30多个用于切片的reducer。除了在每个reducer的末尾添加caseReducers.createSnapshot之外,是否有一种更干净的方法来实现这一点,比如中间件reducer?

q35jwt9p

q35jwt9p1#

你可以创建一个高阶的reducer,它是一个函数,将一个reducer作为参数,并返回一个新的reducer,例如(未测试):

const withSnapshot = reducer => (state, action) => {
  // Call the original reducer
  const tmpState = reducer(state, action);
  // Create the snapshot
  const finalState = createSnapshot(tmpState);
  // Return the state
  return finalState;
}

然后在configureStore中执行以下操作:

mySlice: withSnapshot(mySliceReducer),
iszxjhcz

iszxjhcz2#

.addMatcher允许侦听多个化简器输入

extraReducers(builder) {
    builder
      .addMatcher(isAnyOf(reducer1, reducer2),(state,action)=>{
      // Do something
      })
  }

相关问题