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

后端 未结 5 2005
礼貌的吻别
礼貌的吻别 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:24

    Clone the current state using slice(). By doing this, the original state remains unaffected till setState(). After cloning, do your operations over the cloned array and set it in the state. The previous answer will mutate the state. Read about this here

    let a = this.state.arr.slice(); //creates the clone of the state
    a[index] = "random element";
    this.setState({arr: a});
    

提交回复
热议问题