I am reading the document of Reactjs about not mutating data. I do not understand the difference between 2 pieces of code in document's example:
handleClick() {
// This section is bad style and causes a bug
const words = this.state.words;
words.push('marklar');
this.setState({words: words});
}
and:
handleClick() {
this.setState(prevState => ({
words: prevState.words.concat(['marklar'])
}));
}
Why the second code does not mutate the data?
In the first example you have an array and are adding a new item, by using push
to this array.
In the second example you are creating a copy of the array, by using concat
and adding the item, which means you do not mutate the original array. concat
returns a new array.
In the second example you are not mutating the original array. Not mutating state is an important principle in React and Redux.
There is a good answer here explaining the reasons for avoiding mutation .
简而言之, concat
返回该数组的新副本,因此它不会更改先前的数组。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.