How to edit an item in a state array?

后端 未结 4 468
逝去的感伤
逝去的感伤 2021-01-31 18:08

So here is my state:

this.state = {
  ids: [\'A\', \'E\', \'C\']
};

How would I go about modifying the state so that \'E\' at index 1 is change

4条回答
  •  执笔经年
    2021-01-31 18:24

    Case 1: If you know the index then you can write it like this:

    let ids = [...this.state.ids];     // create the copy of state array
    ids[index] = 'k';                  //new value
    this.setState({ ids });            //update the value
    

    Case 2: If you don't know the index then first use array.findIndex or any other loop to get the index of item you want to update, after that update the value and use setState.

    Like this:

    let ids = [...this.state.ids];  
    let index = ids.findIndex(el => /* condition */);
    ids[index] = 'k';                  
    this.setState({ ids });            
    

提交回复
热议问题