[英]Mutating Data in React.js
I am reading the document of Reactjs about not mutating data. 我正在阅读关于不变异数据的Reactjs 文档 。 I do not understand the difference between 2 pieces of code in document's example:
我不理解文档示例中2条代码之间的区别:
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. 在第一个示例中,您具有一个数组,并通过使用
push
入该数组来添加新项目。
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
并添加该项来创建数组的副本,这意味着您不会更改原始数组。 concat
returns a new array. concat
返回一个新数组。
In the second example you are not mutating the original array. 在第二个示例中,您没有更改原始数组。 Not mutating state is an important principle in React and Redux.
不改变状态是React和Redux中的重要原则。
There is a good answer here explaining the reasons for avoiding mutation . 这里有一个很好的答案,解释了避免突变的原因 。
简而言之, concat
返回该数组的新副本,因此它不会更改先前的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.