reactjs 在Redux中,什么是正确的方法来显示一个方法已经被成功调用?

ds97pgxw  于 2023-11-18  发布在  React
关注(0)|答案(1)|浏览(118)

我希望在Redux切片中调用reducer方法,如果逻辑成功则返回true,如果失败则返回false,但我似乎得到了以下TypeScript错误:
类型“(状态:可调整的吃水,动作:{ payload:{ strategyId:字符串; stageId:字符串;};字体:字符串;})=> boolean'不能赋值给类型'CaseReducer<StrategySlice,{ payload:any; type:string; }>| CaseReducerWithPrepare<StrategySlice,PayloadAction<any,string,any,any>“。
类型“(状态:可调整的吃水,动作:{ payload:{ strategyId:字符串; stageId:字符串;};字体:字符串;})=> boolean'不能分配给类型'CaseReducer<StrategySlice,{ payload:any; type:string; } null '。
类型“boolean”不能赋给类型“void|策略切片|(2322)
我的方法代码如下:

const strategySlice = createSlice({
    name: "strategy",
    initialState,
    reducers: {
deleteStage: (state, action: PayloadAction<{ strategyId: string; stageId: string }>): boolean => {
            const { strategyId, stageId } = action.payload;

            const strategyIndex = findStrategyIndexById(state, strategyId);

            if (strategyIndex !== -1) {
                const strategy = state.strategies[strategyIndex];
                strategy.stages = strategy.stages.filter((stage) => stage.id !== stageId);
                return true;
            } else {
                return false;
            }
});

export const {
    deleteStage,
} = strategySlice.actions;
export default strategySlice.reducer;
        },

字符串
我正在寻求关于最佳实现的建议。我主要是试图防止该方法默默失败,并实现错误处理。

krcsximq

krcsximq1#

你的reducer需要返回一个更新的state(* 或void,因为它使用的是immer,所以修改会被跟踪 *)。
代码返回truefalse
你的reducer应该类似于

deleteStage: (state, action:PayloadAction<{ strategyId: string; stageId: string }>) => {
  const {
    strategyId,
    stageId
  } = action.payload;

  const strategyIndex = findStrategyIndexById(state, strategyId);

  if (strategyIndex !== -1) {
    const strategy = state.strategies[strategyIndex];
    strategy.stages = strategy.stages.filter((stage) => stage.id !== stageId);
  }
});

字符串

相关问题