Storing an object in state of a React component?

后端 未结 6 1165
野趣味
野趣味 2020-12-07 16:05

Is it possible to store an object in the state of a React component? If yes, then how can we change the value of a key in that object using setState? I think it

6条回答
  •  情书的邮戳
    2020-12-07 16:56

    Even though it can be done via immutability-helper or similar I do not wan't to add external dependencies to my code unless I really have to. When I need to do it I use Object.assign. Code:

    this.setState({ abc : Object.assign({}, this.state.abc , {xyz: 'new value'})})
    

    Can be used on HTML Event Attributes as well, example:

    onChange={e => this.setState({ abc : Object.assign({}, this.state.abc, {xyz : 'new value'})})}
    

提交回复
热议问题