How to edit an item in a state array?

后端 未结 4 470
逝去的感伤
逝去的感伤 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:45

    Building on what @mayank-shukla wrote (case 2: knowing the index of the item to replace), this could also be written with Array.splice:

    const replacement = 'B';
    let copy = [...this.state.ids]
    copy.splice(index, 1, replacement)
    
    this.setState({ 
       ids: copy,
    })
    

    REPL Example

    Two things to note, here:

    1. Array.splice is mutative; It will change the array it's operating on, but this is a shallow copy of the array because of the spread operator. More on that below.
    2. You can't directly assign the result of a splice, as the return value of Array.splice is actually the deleted element(s). AKA: Do not assign the result of your slice to the variable you intend to assign to IDs in setState, or you will end up with only the deleted value(s).

    To follow up on shallow vs deep copies from item 1, please note that if you are replacing object references (vs string literals in the question), you will need to use something like lodash's cloneDeep.

    There are a handful of other ways around this, though.

    You can also read more about shallow vs deep on SO itself.

提交回复
热议问题