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?
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?
Share Improve this question edited Apr 10, 2016 at 8:20 angry kiwi asked Apr 10, 2016 at 8:13 angry kiwiangry kiwi 11.5k28 gold badges123 silver badges168 bronze badges2 Answers
Reset to default 5In order to update state you must use setState
method
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
or you can use update
method from React.addons
, to get this method do the following steps
npm i react-addons-update --save
import
(orrequire
) and use itimport 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
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.
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
}
});