React JS maintain array inside state

I am using React state to save some data. For ints and strings, it works well, but unfortunately arrays do not work.

In my component constructor, I have

constructor(props) { super(props); this.state = { terms: 5, myArray: [] } 

and then, I try to save it in the DidUpdate component

 componentDidUpdate() { this.state = { terms: this.state.terms, myArray: this.state.myArray } 

but myArray: this.state.myArray does not work. However, terms: this.state.terms works fine.

Can someone help!

+6
source share
3 answers

The problem is that you are updating the state value incorrectly, update the state value as follows:

 this.setState({ terms: this.state.terms, myArray : this.state.myArray }); 

By DOC :

Never mutate this.state directly, since calling setState () can subsequently replace the mutation you made. Relate to this. As if it's immutable.

Update the state array as follows: first create a copy using slice() , then make the change and use setState to update:

 let arr = this.state.myarr.slice(); arr.push('data'); this.setState({arr}); 
+3
source

You cannot use this.state to update state, you should use:

 this.setState(newStateObject); 
+1
source

You cannot set the state directly, since its array will have to add a value or click a value.

try something like

 var newArray = this.state.myArray.slice(); newArray.push("new value"); this.setState({myArray:newArray}) 

here I sliced ​​to make it immutable.

+1
source

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


All Articles