React .setState()中的传播运算符 [英] Spread operator in React .setState()
问题描述
给出以下从React类组件中提取的片段:
Given the following snippet extracted from a React class component:
constructor(props) {
super(props)
this.state = { active: true }
}
deactivate = () => {
this.setState({ ...this.state, active: false })
}
传播算子进入stopCounter()方法的目的是什么?该应用程序还可以删除它:
What is the aim of the spread operator into the stopCounter() method? The application also works removing it:
deactivate = () => {
this.setState({ active: false })
}
推荐答案
在这种情况下,两者都可以使用,但是您不需要使用它.只需设置状态就可以了:
Both works in that case, but you don't need to use that. Just setting the state will be okay:
this.setState({active: false})
但是让我解释一下,如果您嵌套了以下级别的状态,怎么办:
But let me explain what if you have nested level of states like:
state = {
foo: {
a: 1,
b: 2,
c: 3
}
}
并且当您仅需要更新foo的c状态时,则需要合并以下状态:
And when you need to update the foo's c state only, then you'll need to merge the state like:
this.setState({ foo: {
...this.state.foo,
c: 'updated value'
}})
因此,传播语法将对象与以后的对象合并.它类似于 Object.assign .
So, the spread syntax merges object with later object. It's similar to Object.assign.
这篇关于React .setState()中的传播运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!