如何为嵌套对象设置状态? [英] How do I setState for nested object?

查看:25
本文介绍了如何为嵌套对象设置状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在使用的插件,我必须有一个如下所示的状态:

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: '',
    },
  }
},

如何设置hospital_id 的状态而不设置其他访问权限?

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

这似乎删除了除hospital_id以外的所有内容:

This seems to remove everything but hospital_id:

this.setState({access: {hospital_id: 1}})

推荐答案

您有几个选择:

  1. 借助 ECMA6,您可以使用对象传播提议 (...) 来创建具有更新属性的对象副本.

  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,
  },
});

  • 您可以在对象上使用本机赋值函数 (Object.assign())

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

  • 或者对于最短版本和原子更新:

  • Or for the shortest version and atomic update:

     this.setState(({access}) => ({access: {
       ...access,
       hospital_id: 1,
     }});
    

  • 还有一个选项是更新插件:

  • 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},
      })
    });
    

  • 我建议使用第一个.

    这篇关于如何为嵌套对象设置状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆