How can I insert into React's state array with setState?

后端 未结 5 2023
礼貌的吻别
礼貌的吻别 2021-02-01 18:42

I\'m looking to modify and array in react and insert elements on specific index. This is how my state looks like:

this.state = {arr: [\'\', \'\', \'\', \'\' ]}
<         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 19:40

    UPDATE

    Just use Object.assign() as suggested here to make a copy of your state.

    Thus, you can do it as follows :

    let new_state = Object.assign({}, this.state); 
    let a = new_state.arr;
    a[index] = "random element";
    this.setState({arr: a});
    

    Hope it helps.

提交回复
热议问题