Как исправить Не изменяйте состояние напрямую.Использовать setState () с массивом? - PullRequest
2 голосов
/ 15 мая 2019

У меня есть массив tranches: [{ start: moment().format("HH:mm"), end: moment().format("HH:mm") }], и когда я устанавливаю значение tranches[0].start без setState, я получаю:

Do not mutate state directly. Use setState()

Мой код:

handleAjouter = (start, end, date) => {
    this.state.tranches[0].start = start;
    this.state.tranches[0].end = end;
    this.setState({
      tranches: this.state.tranches
    });
  }

Как я могу это исправить?

1 Ответ

4 голосов
/ 15 мая 2019

Клонируйте объект tranches[0] вместо того, чтобы поменять его, чего вы можете достичь кратко с помощью распространения объекта:

handleAjouter = (start, end, date) => {
  const [firstTranch] = this.state.tranches;
  this.setState({
    tranches: [
      { ...firstTranch, start, end },
      ...tranches.slice(1)  // needed if the array can contain more than one item
    ]
  });
}

Если вам нужно вставить измененный транш по определенному индексу, клонируйте массив и вставьте транш:

const tranches = this.state.tranches.slice();
tranches[index] = { ...tranches[index], someOtherProp: 'foo' };
...