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

时间:2019-05-15 09:45:30

标签: javascript arrays reactjs state setstate

I have an array tranches: [{ start: moment().format("HH:mm"), end: moment().format("HH:mm") }] and when I set the value of the tranches[0].start without setState I get :

Do not mutate state directly. Use setState()

My code is :

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

How can I fix it ?

1 个答案:

答案 0 :(得分:4)

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