如何修复 不要直接改变状态。将 setState() 与数组一起使用?

How to fix Do not mutate state directly. Use setState() with array?

我有一个数组 tranches: [{ start: moment().format("HH:mm"), end: moment().format("HH:mm") }],当我设置没有 setStatetranches[0].start 的值时,我得到:

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

我该如何解决?

克隆 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
    ]
  });
}

如果需要在特定索引处插入更改的 tranch,则克隆数组并插入 tranch:

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