简体   繁体   中英

How to set object state in react

I have the following code:

this.state = { 
    user: null
}

If the user has a name property how would I set it knowing that this.setState({user.name: 'Bob') won't work.

this.setState({ user: {...this.state.user, name: 'Bob'} });
const copy = {...this.state.user}
copy.name = 'Bob'
this.setState({ user: copy })

and if you don't want to override existing properties like say age do this

const copy = {...this.state.user}
copy.name = 'Bob'
this.setState({ user: { ...user, name: copy } })

You can use spread operator for this like:

this.setState(prevState => ({
    user: { ...prevState.user, name: 'Bob' }
}))

For more info:

user itself is probably an object so you can set the state of user to an object

this.setState({ user: { name: "bob" }})

or

this.state = { 
user: {
    name: "bob"
    }
}

If your state contains an object, then you can update the value of nested state using the javascript spread operator. Other user parameters will not be affected.

this.setState({
...this.state,
  user: {
   ...this.state.user,
   name:'Bob'
  }
})

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