简体   繁体   English

reactjs如何更新状态

[英]reactjs how to update state

constructor(){
    super();
    this.state = { 
        address: {
            street:null,
            city:null,
            postalCode: null
        }
    };
}
postalCodeChange(e){
    this.setState.address.postalCode = e.target.value;
    console.log(this.state);
}

I'm trying to update the state, but the postalCode only. 我正在尝试更新状态,但仅限邮政编码。 When the above code execute, I expect to get something like this 当上面的代码执行时,我希望得到这样的东西

Object {address: Object {
           street: null,
           city: null,
           postalCode: 'some new value'
} }

But I got error. 但我得到了错误。 What's wrong? 怎么了?

In order to update state you must use setState method 要更新状态,必须使用setState方法

const state = merge({}, this.state, {
  address: { postalCode: e.target.value }
});

this.setState(state);

Note - merge it is not real function, in order to deep merge objects you can use packages like merge-deep , assign-deep 注意 - merge它不是真正的函数,为了深度合并对象,你可以使用像merge-deepassign-deep

or you can use update method from React.addons , to get this method do the following steps 或者您可以使用React.addons update方法,以获取此方法执行以下步骤

  1. npm i react-addons-update --save
  2. import (or require ) and use it import (或require )并使用它

     import update from 'react-addons-update'; const state = update(this.state, { address: { postalCode: { $set: e.target.value } } }); this.setState(state); 

Example

also if you use ES2015 you can use Object.assign , or spread operator 如果您使用ES2015也可以使用Object.assignspread operator

Object.assign : Object.assign

const state = Object.assign({}, this.state, {
   address: Object.assign({}, this.state.address, { postalCode: 1000 })
});

spread operator

const newState = {
  address: { ...state.address, postalCode: 1000 }
};

I saw that you are using ES6, so I'm assuming you can also use the stage-2 object spread operator . 我看到你使用的是ES6,所以我假设你也可以使用stage-2对象扩展运算符

By using that feature, you can update your state without additional plugin or lots of code. 通过使用该功能,您可以更新您的状态,而无需额外的插件或大量代码。

this.setState({
    address: {
        ...this.state.address,
        postalCode: e.target.value
    }
});

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

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