在Redux Toolkit中,我可以从不同切片中的extraReducer函数调用切片中定义的reducer函数吗?

lsmepo6l  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(199)

基本上,我必须根据为不同切片定义的异步形实转换程序的结果更改一个切片的状态。如果不可能,建议采用哪种方法?
根据ChatGPT的建议,我试着打电话

  1. action.payload.dispatch(increment());

字符串
其中increment是从切片“A”的缩减
sliceA.js

  1. import { createSlice } from '@reduxjs/toolkit';
  2. const sliceA = createSlice({
  3. name: 'sliceA',
  4. initialState: {
  5. countA: 0,
  6. },
  7. reducers: {
  8. increment: (state) => {
  9. state.countA += 1;
  10. },
  11. },
  12. });
  13. export const { increment } = sliceA.actions;
  14. export default sliceA.reducer;


然后在切片B中调用A的增量reducer
sliceB.js

  1. import { createSlice } from '@reduxjs/toolkit';
  2. import { increment } from './sliceA'; // Import the "increment" action from sliceA
  3. const sliceB = createSlice({
  4. name: 'sliceB',
  5. initialState: {
  6. countB: 0,
  7. },
  8. reducers: {
  9. someReducerInSliceB: (state, action) => {
  10. // Your reducer logic for sliceB
  11. },
  12. },
  13. extraReducers: (builder) => {
  14. builder.addCase('exampleAction', (state, action) => {
  15. // Dispatch the "increment" action from sliceA
  16. action.payload.dispatch(increment()); // This will update the countA in sliceA
  17. });
  18. },
  19. });
  20. export const { someReducerInSliceB } = sliceB.actions;
  21. export default sliceB.reducer;


它会导致运行时错误:“action.payload.dispatch不是函数”。

nzk0hqpo

nzk0hqpo1#

Reducer函数对ThunkAPI或dispatch函数没有直接操作。Reducer是纯函数,所以它们不应该有像分派操作这样的副作用。你也不是直接调用reducer函数,而是将动作分派到store,store调用根reducer函数,并将当前状态对象和动作传递给它,向下传播reducer树以计算下一个状态值。
如果我对您的问题理解正确的话,您希望在分派“exampleAction”操作时,片A和片B中的某些状态都要更新。切片A还可以声明一个额外的reducer case来处理相同的操作并应用自己的逻辑。
示例如下:

  1. const sliceA = createSlice({
  2. name: 'sliceA',
  3. initialState: {
  4. countA: 0,
  5. },
  6. reducers: {
  7. increment: (state) => {
  8. state.countA += 1;
  9. },
  10. },
  11. extraReducers: (builder) => {
  12. builder.addCase('exampleAction', (state, action) => {
  13. state.countA += 1;
  14. });
  15. },
  16. });

字符串
如果你想让代码更 * DRY *,那么你可以把reducer函数抽象成一个函数。

  1. const increment = (state, action) => {
  2. state.countA += 1;
  3. };
  4. const sliceA = createSlice({
  5. name: 'sliceA',
  6. initialState: {
  7. countA: 0,
  8. },
  9. reducers: {
  10. increment,
  11. },
  12. extraReducers: (builder) => {
  13. builder.addCase('exampleAction', increment);
  14. },
  15. });

展开查看全部

相关问题