【问题标题】:Cannot update state with spread operator in React无法在 React 中使用扩展运算符更新状态
【发布时间】:2018-06-25 07:28:06
【问题描述】:

我是 React 新手,我只是不知道如何使用扩展运算符将定义的数组中的新元素推入状态。 目的是获取一个包含不同数字序列的数组,代码如下:

getSequence = () => {
    let n = 0;

    while ( n < 3 ) {
      let number = Math.floor(Math.random() * 10) + 1;
      let exists = this.state.sequence.indexOf(number);

      if ( exists < 0 ) {
        this.setState({
          sequence: [...this.state.sequence, number]
        });

        n++;
      }
    }
  }

该事件由 onClick 事件触发,但每次单击时,数组将仅更新一个数字。 我哪里错了?

【问题讨论】:

  • setState 是一个异步函数,我认为它在 while 循环中不会像您预期的那样工作。

标签: javascript reactjs redux spread-syntax


【解决方案1】:

变化:

1- setState is async,所以它不会像你期望的那样工作。根据文档:

setState() 并不总是立即更新组件。有可能 批处理或推迟更新。这使得阅读 this.state 就在调用 setState() 之后,这是一个潜在的陷阱。

2- 在循环中使用setState 不是一个好主意,首先创建三个数字的数组,然后简单地将其合并到状态数组中。

3- 如果新的状态值依赖于先前的状态,则使用更新函数而不是 setState 内的 this.state

查看这个答案:Why calling setState method doesn't mutate the state immediately?

这样写:

getSequence = () => {
    let n = 0, arr = [];

    while ( n < 3 ) {
        let number = Math.floor(Math.random() * 10) + 1;
        let exists = this.state.sequence.indexOf(number);

        if ( exists < 0 ) {
            arr.push(number);
            n++;
        }
    }

    this.setState(prevState => ({
        sequence: [...prevState.sequence, ...arr]
    }));
}

【讨论】:

  • 谢谢,它就像一个魅力!问题确实是 setState() 是一个异步函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
  • 2019-07-27
  • 2021-03-25
  • 1970-01-01
  • 2021-12-01
  • 2021-03-16
  • 2017-06-12
相关资源
最近更新 更多