这是一个基本问题。我已经开始学习React,并且我有一个作业,我必须通过递增和递减按钮更改值。我已经使用类组件方式实现了它。
但我有一个疑问。请参考下面的代码,其中值会更改。
increment = () => {
this.setState({
count: this.state.count + 1 //HERE -----------------
});
};
为什么不是这样?
increment = () => {
this.setState({
this.state.count: this.state.count + 1 // Here ...ERROR COMES
});
};
那么为什么不像this.state.count这样访问它:this.state.count + 1 ?? 请让我知道原因。
不起作用的原因是因为在对象内分配值的语法与分配普通变量的语法不同。
详细说明:
创建对象时,请使用以下语法:
let myObj = {
foo: 'bar'
}
或者您可以这样做:
let myObj = {}
myObj.foo = 'bar'
但是你做不到
let myObj = {
myObj.foo: 'bar'
}
该setState
函数的作用是创建一个新对象并将其传递给函数。
您应该像这样轻松地编写它:
const newState = { count: this.state.count + 1 }
this.setState(newState);
这就是为什么必须使用第一种语法的原因。
然后,setState
将您给它的对象与当前对象合并,this.state
在下一个渲染this.state
中将包含更新后的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句