2

I'm using Redux Toolkit and I'm having trouble in one of my actions. Here's relevant parts of my slice:

export const initialCookingSessionState = {
  recipeInfo: null as RecipeInfo | null,
  instructions: [] as Instruction[],
  ingredients: [] as Ingredient[],
  activeTimers: [] as CookingTimer[],
  currentStepIndex: 0 as number,
  stepTimers: [] as StepTimer[]
};

const cookingSessionSlice = createSlice({
  name: 'session',
  initialState: initialCookingSessionState,
  reducers: {
    startRecipe(state, { payload: recipe }: PayloadAction<Recipe>) {
      const { info, instructions, ingredients } = recipe;
      state.recipeInfo = info;
      state.ingredients = [...ingredients];
      state.instructions = [...instructions]

      state.stepTimers = [];
      state.instructions.forEach(({ timers }, stepIndex) => {
        timers.forEach(timer =>
          state.stepTimers.push({ ...timer, stepIndex, state: CookingTimerState.Pending })
        )
      })
    },
    incStep(state) { state.currentStepIndex++ },

    decStep(state) { state.currentStepIndex-- },

    startTimer(state, { payload: timer }: PayloadAction<StepTimer>) {
      timer.state = CookingTimerState.Running  
    },
  }
});

When I dispatch startTimer, I get the error:

Cannot assign to read only property 'state' of object '#'

There must be something about what is and isn't possible with Redux Toolkit's "Mutative State Changes" that I'm missing. It seems to me that my example isn't that different from theirs in the docs, but apparently I'm wrong about that. (the other actions work fine)

In case it's helpful, here are the models, which I think are pretty simple:

export class Recipe {
  info: RecipeInfo = {
    id: "",
    title: ""
  };
  instructions: Instruction[] = [];
  ingredients: Ingredient[] = []
}

export class Instruction {
  timers: CookingTimer[] = [];

  constructor(public text: string) {}
}

export class Ingredient {
  id: string = "";
  state: IngredientState = { done: false };

  constructor(public text: string) {}
}

export class CookingTimer {
  constructor(
    public durationSec = 0,
    public label = "") {}
} 

export enum CookingTimerState {
  Pending, Paused, Running, Done
}

export type StepTimer = {
  state: CookingTimerState
  durationSec: number
  label: string
  stepIndex: number
}

You didn't initialize the list ListOfSheets in the SheetListModel. Initialize the list in the constructor:

public class SheetListModel
{
     public SheetListModel()
     {
          ListOfSheets = new List<Sheets>();
     }

      public List<Sheets> ListOfSheets { get; set; }
}

Or you can achieve the same with the shorter syntax:

public class SheetListModel
{
    public List<Sheets> ListOfSheets { get; set; } = new List<Sheets>();
}
4

0 回答 0