How to edit an element in an array of states?

So here is my condition:

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

How do I change the state modification so that “E” in index 1 is changed to “B”? Such as:

this.setState({
  ids[1]: 'B'
});

How to do it?

+12
source share
4 answers

My suggestion is to get used to using immutable operations so as not to change the object of the internal state.

As indicated in the reference documentation :

Never modify this.state directly, as calling setState () later on can replace the mutation you made. Treat this condition as unchanging.

[1] slice() , [2] , [3] setState . .

- :

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

1: , :

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

2: , array.findIndex , , , setState.

:

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

, @mayank-shukla ( 2: ), Array.splice:

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

this.setState({ 
   ids: copy,
})

REPL

:

  1. Array.splice ; , , - . .
  2. , Array.splice (). AKA: , setState, .

To continue exploring the shallow and deep copies from point 1, note that if you replace object references (instead of string literals in the question), you need to use something like lodash cloneDeep .

Although there are several other ways around this .

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

0
source

Here is another solution for changing a specific array index in setState:

this.setState({
  ...array,
  Object.assign([...array], { [id]: yourNewObjectOrValue })
})
0
source

Source: https://habr.com/ru/post/1668787/


All Articles