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

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

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

action.payload.dispatch(increment());

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

import { createSlice } from '@reduxjs/toolkit';

const sliceA = createSlice({
  name: 'sliceA',
  initialState: {
    countA: 0,
  },
  reducers: {
    increment: (state) => {
      state.countA += 1;
    },
  },
});

export const { increment } = sliceA.actions;
export default sliceA.reducer;


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

import { createSlice } from '@reduxjs/toolkit';
import { increment } from './sliceA'; // Import the "increment" action from sliceA

const sliceB = createSlice({
  name: 'sliceB',
  initialState: {
    countB: 0,
  },
  reducers: {
    someReducerInSliceB: (state, action) => {
      // Your reducer logic for sliceB
    },
  },
  extraReducers: (builder) => {
    builder.addCase('exampleAction', (state, action) => {
      // Dispatch the "increment" action from sliceA
      action.payload.dispatch(increment()); // This will update the countA in sliceA
    });
  },
});

export const { someReducerInSliceB } = sliceB.actions;
export default sliceB.reducer;


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

nzk0hqpo

nzk0hqpo1#

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

const sliceA = createSlice({
  name: 'sliceA',
  initialState: {
    countA: 0,
  },
  reducers: {
    increment: (state) => {
      state.countA += 1;
    },
  },
  extraReducers: (builder) => {
    builder.addCase('exampleAction', (state, action) => {
      state.countA += 1;
    });
  },
});

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

const increment = (state, action) => {
  state.countA += 1;
};

const sliceA = createSlice({
  name: 'sliceA',
  initialState: {
    countA: 0,
  },
  reducers: {
    increment,
  },
  extraReducers: (builder) => {
    builder.addCase('exampleAction', increment);
  },
});

相关问题