设置对象数组的状态

时间:2020-04-04 16:17:04

标签: javascript arrays reactjs

我有一个处于状态的对象数组,我想使用this.setState更改该数组的状态。

 state = {
   randomNumbers: [{ value: 6 }, { value: 3 }, { value: 2 }]
 };

我想用随机值更新这些数字。 如何在函数中更新这些值。

handleUpdate = () => {
 let randomFirst = Math.floor(Math.random() * 6) + 1;
 let randomSecond = Math.floor(Math.random() * 6) + 1;
 let randomThird = Math.floor(Math.random() * 6) + 1;
 //i have to set state here and assign these three random numbers values to state values one by one.
 this.setState(?);
}

3 个答案:

答案 0 :(得分:1)

您可以按照以下步骤进行操作,但是为什么这样做:

  • 您是否使用大写字母表示变量,属性?
  • 您是否使用具有value属性的对象,难道它本身不只是使用数字吗?
        this.setState(() => ({
          RandomNumbers: [
            { value: RandomFirst },
            { value: RandomSecond },
            { value: RandomThird },
          ],
        }));

答案 1 :(得分:1)

使用map()避免重复自己。

handleUpdate = () => {
  this.setState(prevState => ({
    RandomNumbers: prevState.RandomNumbers.map(x => ({
      value: Math.floor(Math.random() * 6) + 1
    }))
  }));
};

答案 2 :(得分:1)

handleUpdate = () => {
 this.setState({
   RandomNumbers: [
     { value: Math.floor(Math.random() * 6) + 1},
     { value: Math.floor(Math.random() * 6) + 1},
     { value: Math.floor(Math.random() * 6) + 1},
   ],
 });
}