简体   繁体   English

更新嵌套的setState对象 - ReactJS

[英]Update nested setState Object - ReactJS

this.state = {
    qs: {catName:'',subCatName:''}
}

I have the above nested state object. 我有上面嵌套的状态对象。 In order to setState, I used the below code in componentDidUpdate. 为了setState,我在componentDidUpdate中使用了以下代码。

var newQs = {...this.state.qs}
newQs.catName = 'name';
this.setState({qs: newQs});

But it does not working, still this.state.qs is empty not updated. 但它不起作用,仍然this.state.qs为空未更新。 I even tried the following one. 我甚至试过以下一个。

this.setState({...this.state, qs: {
    ...this.state.qs,
    catName: 'name'
}});

Still not works. 仍然没有用。

Use setState like this: 像这样使用setState:

this.setState( prevState =>
    ( { qs: { ...prevState.qs, catName: 'name' } } )
)

You don't need here ...this.state since React merges other parts of your state. 你不需要这里...this.state因为React合并了你所在州的其他部分。

Also I edited my suggestion according to @kuby's comment. 我也根据@ kuby的评论编辑了我的建议。 React now recommends using a function with prevState instead of directly setting the state. React现在建议使用带有prevState的函数,而不是直接设置状态。 This is because state updates may be asynchronous. 这是因为状态更新可能是异步的。 So, using a function is a better approach here. 因此,使用函数是一种更好的方法。 If we don't use a function that does not mean always there will be problems but there could be and being in the safe side is always a better approach. 如果我们不使用并不意味着总是存在问题的功能,但可能存在且安全方面始终是更好的方法。

Related doc: https://reactjs.org/docs/state-and-lifecycle.html 相关文档: https//reactjs.org/docs/state-and-lifecycle.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM