[英]spread in setState of react
I saw this in somewhere and I'm confused. 我在某个地方看到了这个,我很困惑。 I've never do thing this way, what it does actually?
我从来没有这样做过,实际上它是做什么的?
doSomething = index => {
const tempState = this.state
tempState.keys.push(index)
this.setState({
...tempState
})
}
const tempState = this.state
The above assigns to tempState
a reference to the state object 上面为
tempState
分配了对状态对象的引用
tempState.keys.push(index)
tempState
has a property of keys that holds a reference to an array and push is called on the array to add index
to the array tempState
具有键的属性,该属性保存对数组的引用,并在数组上调用push以向数组添加index
this.setState({
...tempState
})
this.setState
is called and a new copy of the state is passed into setState
. this.setState
并将状态的新副本传递到setState
。 The spread operator is basically copying the content of the old state into a new object. 传播运算符基本上是将旧状态的内容复制到新对象中。
The above implementation isn't the perfect one and should be improved so that you aren't mutating the original state object. 上面的实现不是完美的实现,应该对其进行改进,以免改变原始状态对象。
doSomething = index => {
const tempState = this.state // assing reference of state to tempState
tempState.keys.push(index) // push a value to `keys` property value within state. Note that Javascript object assignment works by reference and hence this will actually mutate the state object
this.setState({
...tempState
}) // call setState to update state and pass the cloned version of tempState using spread syntax as the new state values
}
Although the above implementation clones the value before setState, its incorrect since it should clone the value before any update is made into it 尽管上述实现在setState之前克隆了该值,但它是不正确的,因为它应该在对其进行任何更新之前克隆该值
doSomething = index => {
const keys = [...this.state.keys]
keys.push(index)
this.setState({
keys
})
}
However since you use ES5, in order to clone the value, you can make use of concat to update the keys array using functional setState like 但是,由于您使用ES5,因此为了克隆值,可以使用concat使用setState之类的功能来更新键数组。
doSomething = index => {
this.setState(prevState => ({
keys: prevState.keys.concat([index])
}))
}
I hope the above answer provides an insight into the explanation that you were looking for 希望以上答案能为您提供所需的解释的见解
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.