[英]Do I need “…this.state” when calling this.setState()
I can't seem to find a consistent example of how to properly set state in React. 我似乎找不到如何在React中正确设置状态的一致示例。
Say, I've got my component that has the state: 说,我的组件处于以下状态:
state = {
propertyOne: 'abc',
propertyTwo: 'def',
propertyThree: 'ghi',
}
If I wanted to change propertyOne I would (at the moment) do: 如果我想更改propertyOne,我会(目前)这样做:
this.setState({...this.state, propertyOne: 'new value'})
I assumed this was needed to 'remember' the other two values, however, it appears if I do not include ...this.state
the other two values still remain. 我认为这是“记住”其他两个值所必需的,但是,如果我不包括...this.state
则仍然保留其他两个值。
this.setState({propertyOne: 'new value'})
So, my question is, do I need ...this.state
? 所以,我的问题是,我需要...this.state
吗? Why do some people on the internet seem to suggest using it? 为什么有些人在互联网上似乎建议使用它?
状态更新已合并,请在此处阅读更多有关setState的React文档
The answer is YES if you use an older version of react (I think before version 16 or 15, but not 100% sure which one exactly). 如果您使用的是较早版本的react(我认为在版本16或15之前,但不能100%确切地确定哪个版本),答案是肯定的。 If you use version 16 and later, you don't have to 如果使用版本16和更高版本,则不必
In case when you directly want to update a state value, you don't need to make use of spread syntax to update state. 如果您直接想要更新状态值,则无需使用传播语法来更新状态。 State updates are merged automatically. 状态更新会自动合并。
However in spread is needed when you want to update a particular state value for instance appending data to an array. 但是,当您要更新特定状态值(例如将数据附加到数组)时,需要进行扩展。
state = {
data: ['1']
}
this.setState(prevState => ({
data: [...prevState.data, 2]
}))
As other have answered. 正如其他人回答的那样。 this.setState({propertyOne: 'new value'})
is correct. this.setState({propertyOne: 'new value'})
是正确的。 React will automatically copy {propertyOne: 'abc',propertyTwo: 'def', propertyThree: 'ghi'}
. React将自动复制{propertyOne: 'abc',propertyTwo: 'def', propertyThree: 'ghi'}
。 And put them in the new state of the function along with the new key and value {propertyOne: 'new value'}
. 并将它们与新键和值{propertyOne: 'new value'}
一起置于函数的新状态。 React only updates the key specified in the this.setState()
React只更新this.setState()
指定的密钥
Important note: If key propertyOne
already has the value of 'new value'
React will not update the state at all. 重要说明:如果键propertyOne
已经具有'new value'
的值,那么React根本不会更新状态。 React does a key value comparison to see if the contents of this.setState()
are the same as this.state
. 反应没有一个关键值进行比较,以查看是否内容this.setState()
是相同的this.state
。 React does this to ensure the least number of updates for a component. React这样做是为了确保组件的最少更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.