I am using React with ES2015. I have this in my state:
this.state = { info: {
merchandise: {
label: '',
visible: false
},
hotels: {
label: '',
visible: false
}
}
}
I'm try to update state with this code:
this.setState({info.merchandise.label: "New Label"})
but I get an error whereas I can log the value of this.state.info.merchandise.label
without any issues. What am I doing wrong?
I believe you can only use setState()
on a direct property of this.state
.
What you could do in this situation is
state
property you want to work with this.state
Like so:
let temp = Object.assign({}, this.state.info);
temp.merchandise.label = "New Label";
this.setState(info: temp);
You can do following,
let newState = this.state;
newState.info.merchandise.label = "New Label";
this.setState(newState);
According to React's setState doc :
Performs a shallow merge of nextState into current state
This means you should provide a valid nextState
object as argument to the method. {info.merchandise.label: "New Label"}
is not syntactically correct, that's why you get an error.
Treat this.state as if it were immutable.
This simply means that if you want to change some property inside the state object, you should not mutate it directly, but replace it with a new object containing the modification instead.
In your case, the state object contains several nested objects. If you want to modify a "leaf" object's property, you'll also have to provide new objects for every containing object up the tree (because each of them have a property that changes in the process). Using Object.assign() to create new objects, you could write:
// new "leaf" object:
const newMerchandise = Object.assign({}, this.state.info.merchandise,
{label: "New Label"});
// new "parent" object:
const newInfo = Object.assign({}, this.state.info,
{merchandise: newMerchandise});
// new state ("parent") object:
const newState = Object.assign({}, this.state,
{info: newInfo});
// eventually:
this.setState(newState);
By the way, you'll notice that it's easier to handle the state object when its structure tends to be "flat" rather than "deeply nested".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.