简体   繁体   中英

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.

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. I even tried the following one.

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

Still not works.

Use setState like this:

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

You don't need here ...this.state since React merges other parts of your state.

Also I edited my suggestion according to @kuby's comment. React now recommends using a function with prevState instead of directly setting the state. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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