使用setstate更改状态

时间:2020-03-05 07:47:17

标签: reactjs setstate

constructor(props){
   super(props);
   this.state = {
   option:[
      {first:1,id:1}
      {first:2,id:2},
     {first:3,id:3}
]
}

如何通过setstate更改选项状态为first:2的第二个元素的值。 任何帮助将不胜感激?

1 个答案:

答案 0 :(得分:4)

使用.map()更新数组中的对象,而不会改变状态。

this.setState(prevState => ({
  option: prevState.option.map(op => ( op.first == 2 ? { ...op, first:4 } : op ))
}));

这会将first:2更新为first:4