Невозможно назначить только для чтения свойство 'состояние' объекта '# <Object>' - PullRequest
0 голосов
/ 17 апреля 2020

Я использую Redux Toolkit и у меня возникают проблемы с одним из моих действий. Вот соответствующие части моего среза:

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  
    },
  }
});

Когда я отправляю startTimer, я получаю ошибку:

Невозможно назначить только для чтения свойство 'state' объекта '# '

Должно быть что-то о том, что есть, а что нет, в Redux Toolkit "Изменения состояний", которые я пропускаю. Мне кажется, что мой пример ничем не отличается от их в документах, но, видимо, я ошибаюсь по этому поводу. (другие действия работают нормально)

В случае, если это полезно, вот модели, которые я считаю довольно простыми:

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
}
...