我有一个数组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
    });
  }


我该如何解决?

最佳答案

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

关于javascript - 如何解决不要直接改变状态。将setState()与数组一起使用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56146300/

10-10 00:29