【问题标题】:How to fix Do not mutate state directly. Use setState() with array?如何修复 不要直接改变状态。将 setState() 与数组一起使用?
【发布时间】:2019-10-02 10:02:18
【问题描述】:

我有一个数组 tranches: [{ start: moment().format("HH:mm"), end: moment().format("HH:mm") }],当我在没有 setState 的情况下设置 tranches[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
    });
  }

我该如何解决?

【问题讨论】:

    标签: javascript arrays reactjs state setstate


    【解决方案1】:

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

    【讨论】:

    • 谢谢@CertainPerformance,如果我有this.state.tranches[selectedIndex] = { ...this.state.tranches[selectedIndex], [startOrEnd]: textValue };
    • 先切片整个数组,然后你可以重新分配所需索引处的元素
    • 我尝试了 const tranches = this.state.tranches.slice(); tranches[selectedIndex] = { ...tranches[selectedIndex], [startOrEnd]: textValue }; this.setState({ tranches:this.state.tranches }); 但它不起作用。
    • 您将新状态设置为与旧状态完全相同。使用 new tranches 数组调用 setStatethis.setState({ tranches });
    猜你喜欢
    • 2019-07-10
    • 1970-01-01
    • 2017-11-19
    • 2021-11-28
    • 2018-04-24
    • 2019-12-22
    • 2017-09-27
    • 1970-01-01
    • 2017-03-05
    相关资源
    最近更新 更多