How to edit an item in a state array?

后端 未结 4 473
逝去的感伤
逝去的感伤 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条回答
  •  梦毁少年i
    2021-01-31 18:22

    My suggestion is to get used to use immutable operations, so you don't modify internal state object.

    As pointed in the react docs:

    Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

    In this case, you can [1] use slice() to get a new copy of the Array, [2] manipulate the copy, and, then, [3] setState with the new Array. It's a good practice.

    Something like that:

    const newIds = this.state.ids.slice() //copy the array
    newIds[1] = 'B' //execute the manipulations
    this.setState({ids: newIds}) //set the new state
    

提交回复
热议问题