简体   繁体   English

如何在反应中设置 object state

[英]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.如果用户有一个 name 属性,我将如何设置它知道this.setState({user.name: 'Bob')不起作用。

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用户本身可能是 object 因此您可以将用户的 state 设置为 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.如果您的 state 包含 object,那么您可以使用 ZDE9B9ED708D7E2E1DCEEFFEEFEEFEE87 更新嵌套 state 的值。 Other user parameters will not be affected.其他用户参数不受影响。

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

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

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