constructor(){
super();
this.state = {
address: {
street:null,
city:null,
postalCode: null
}
};
}
postalCodeChange(e){
this.setState.address.postalCode = e.target.value;
console.log(this.state);
}
我正在尝试更新状态,但仅更新邮政编码。当上面的代码执行时,我希望得到这样的结果
Object {address: Object {
street: null,
city: null,
postalCode: 'some new value'
} }
但是我得到了错误。怎么了?
最佳答案
为了更新状态你必须使用setState
方法
const state = merge({}, this.state, {
address: { postalCode: e.target.value }
});
this.setState(state);
注意 - merge
它不是真正的函数,为了深度合并对象你可以使用像merge-deep
这样的包, assign-deep
或者您可以使用 update
方法来自 React.addons
, 要获得此方法,请执行以下步骤
npm i react-addons-update --save
import
(或require
)并使用import update from 'react-addons-update'; const state = update(this.state, { address: { postalCode: { $set: e.target.value } } }); this.setState(state);
另外,如果你使用 ES2015
,你可以使用 Object.assign
, 或 spread operator
Object.assign
:
const state = Object.assign({}, this.state, {
address: Object.assign({}, this.state.address, { postalCode: 1000 })
});
展开运算符
const newState = {
address: { ...state.address, postalCode: 1000 }
};
关于javascript - reactjs如何更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36527426/