【发布时间】: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