[英]spread in setState of react
我在某个地方看到了这个,我很困惑。 我从来没有这样做过,实际上它是做什么的?
doSomething = index => {
const tempState = this.state
tempState.keys.push(index)
this.setState({
...tempState
})
}
const tempState = this.state
上面为tempState
分配了对状态对象的引用
tempState.keys.push(index)
tempState
具有键的属性,该属性保存对数组的引用,并在数组上调用push以向数组添加index
this.setState({
...tempState
})
this.setState
并将状态的新副本传递到setState
。 传播运算符基本上是将旧状态的内容复制到新对象中。
上面的实现不是完美的实现,应该对其进行改进,以免改变原始状态对象。
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
}
尽管上述实现在setState之前克隆了该值,但它是不正确的,因为它应该在对其进行任何更新之前克隆该值
doSomething = index => {
const keys = [...this.state.keys]
keys.push(index)
this.setState({
keys
})
}
但是,由于您使用ES5,因此为了克隆值,可以使用concat使用setState之类的功能来更新键数组。
doSomething = index => {
this.setState(prevState => ({
keys: prevState.keys.concat([index])
}))
}
希望以上答案能为您提供所需的解释的见解
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.