问题描述
constructor(){
super();
this.state = {
address: {
street:null,
city:null,
postalCode: null
}
};
}
postalCodeChange(e){
this.setState.address.postalCode = e.target.value;
console.log(this.state);
}
我正在尝试更新状态,但仅更新 postalCode.当上面的代码执行时,我希望得到这样的东西
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?
推荐答案
为了更新状态,你必须使用 setState
方法
In order to update state you must use setState
method
const state = merge({}, this.state, {
address: { postalCode: e.target.value }
});
this.setState(state);
注意 - merge
它不是真正的功能,为了深度合并对象,你可以使用像 merge-deep
, assign-deep
Note - merge
it is not real function, in order to deep merge objects you can use packages like merge-deep
, assign-deep
或者您可以使用 update
方法来自React.addons
,让这个方法做以下步骤
or you can use update
method from React.addons
, to get this method do the following steps
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
also if you use ES2015
you can use Object.assign
, or 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 }
};
这篇关于reactjs如何更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!