How do I setState for nested object?

后端 未结 5 628
鱼传尺愫
鱼传尺愫 2020-11-29 20:36

For a plugin I\'m using I have to have a state that looks like this:

getInitialState() {
  return {
    invalid: true,
    access: {
      access_code: \'\',         


        
5条回答
  •  执笔经年
    2020-11-29 21:02

    My preferred way of doing this now is as simple as:

    let newAccess = this.state.access;
    newAccess.hospital_id = 1;
    setState({access: newAccess});
    

    Slightly simpler than the current accepted answer.

    EDIT (based on the question from @SILENT )

    It looks like this is actually a potentially dangerous method. Further reading here React: A (very brief) talk about immutability.

    Looks like a better way to do this would be:

    let newAccess = Object.assign({}, this.state.access, {hospital_id:1});
    this.setState({access: newAccess});
    

提交回复
热议问题