如何在createSlice中调用其他reducer改变状态?

How to call other reducers in createSlice to change state?

我使用 redux 来 createSlice,这是我的 createSlice 的样子:

export default createSlice({
    name:'testSlice',
    initialState,
    reducers:{
        setRecords: setRecordsReducer,
        setObjects: setObjectsReducer,
        setBoth:....
    }
});

这是 setRecordsReducer 和 setObjectsReducer 的样子:

const setRecordsReducer = (state, {payload:{id,recordName}}) => {
    return {...state, items:{...state.items, records:{...state.items.records, [id]:{recordName}};
};

const setObjectsReducer = (state, {payload:{id,objectName}}) => {
    return {...state, objects:{...state.objects, records:{...state.objects.records, [id]:{objectName}};
};

两个reducer setRecordReducer 和setObjectsReducer 改变状态的不同部分(实际上不是改变状态,而是基于它构建新的状态)。 setRecordReducer returns 新状态基于state.items.records; setObjectReducer returns 新状态基于 state.objects.records.

我尝试创建一个新的动作 setBoth,当动作 setBoth 发生时,我可以同时调用 setRecordReducer 和 setObjectsReducer 吗?所以状态的两个部分可以改变并且return我是新状态?

既然每个状态都在运行,那么是的,我看不出你为什么不能编写一个调用其他函数并传递适当参数的 reducer 函数。这个新的 reducer 函数还需要 return 下一个计算的状态值,returned 来自每个调用的 reducer 函数的组合更新状态。

const setBothReducer = (state, action) => {
  return {
    ...state,
    ...setRecordsReducer(state, action),
    ...setObjectsReducer(state, action),
  };
}

export default createSlice({
  name:'testSlice',
  initialState,
  reducers:{
    setRecords: setRecordsReducer,
    setObjects: setObjectsReducer,
    setBoth: setBothReducer,
  }
});