Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - How do I setState for nested object?

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

getInitialState() {
  return {
    invalid: true,
    access: {
      access_code: '',
      zipcode: '',
      password: '',
      confirm: '',
      hospital_id: '',
    },
  }
},

How would I set the state of hospital_id without setting the rest of access?

This seems to remove everything but hospital_id:

this.setState({access: {hospital_id: 1}})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have a few options:

  1. With ECMA6, you can use the Object spread proposal (...) to create copies of objects with updated properties.

    this.setState({
      access: {
        ...this.state.access,
        hospital_id: 1,
      },
    });
    
  2. You can use the native assign function on the Object (Object.assign())

    this.setState({
      access: Object.assign({}, this.state.access, {
        hospital_id: 1,
      }),
    });
    
  3. Or for the shortest version and atomic update:

     this.setState(({access}) => ({access: {
       ...access,
       hospital_id: 1,
     }});
    
  4. And one more option is the updates addon:

    var update = require('react-addons-update');
    // per React docs 
    // https://reactjs.org/docs/update.html 
    // , you may want to change this to 
    // import update from 'immutability-helper';
    this.setState({
      access: update(this.state.access, {
        hospital_id: {$set: 1},
      })
    });
    

I would recommend using the first one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...