Javascript 如何在React中更改状态对象内的键的状态?
我在Javascript 如何在React中更改状态对象内的键的状态?,javascript,reactjs,Javascript,Reactjs,我在React.Component类中具有以下状态: this.state = { stuff: { stuffData: [], loading: true, }, moreStuff: { ... } } 在函数内部,单击按钮后,我想将填充的状态更新为加载 如果我按以下方式操作,它会起作用: const { stuff } = this.state; const newStuff = stuff; newStuff.loading = true; thi
React.Component
类中具有以下状态:
this.state = {
stuff: {
stuffData: [],
loading: true,
},
moreStuff: {
...
}
}
在函数内部,单击按钮后,我想将填充
的状态更新为加载
如果我按以下方式操作,它会起作用:
const { stuff } = this.state;
const newStuff = stuff;
newStuff.loading = true;
this.setState({ stuff: newStuff };
但我想这样做(没有得到预期的结果):
我错过了什么 首先复制对象,然后更改要更改的值
const { stuff } = this.state;
this.setState({
stuff: {
...stuff,
loading: true
}
});
因为
如果rest={a:2,b:3}
将为您提供{a:1,…rest}
{a:2,b:3}
将为您提供{…rest,a:1}
{a:1,b:3}
const { stuff } = this.state;
this.setState({
stuff: {
...stuff,
loading: true
}
});
因为
如果rest={a:2,b:3}
将为您提供{a:1,…rest}
{a:2,b:3}
将为您提供{…rest,a:1}
{a:1,b:3}
{…stuff,loading:true}
,这与Object.assign(stuff,{loading:true})
相同stuff
是基本对象,您正在覆盖加载变量。@Santa'sLittleHelper这与对象不同。assign
将变异stuff
,而spreading不会变异stuff
@EmileBergeron您是对的。我的错误。您正在使用扩展运算符覆盖加载的值。我还认为,第一种方法很好,你已经用另一种方法做了。应该是{…stuff,loading:true}
,这与Object.assign(stuff,{loading:true})
相同stuff
是基本对象,您正在覆盖加载变量。@Santa'sLittleHelper这与对象不同。assign
将变异stuff
,而spreading不会变异stuff
@EmileBergeron您是对的。我的错误。