Lets say I initialize the state of a component like so:
getInitialState: function(){
return {name: "Bob Smith",
phone: "555-555-5555",
location: "San Francisco, CA",
best-friend: "Bill Jacobson",
favorite-color: "Orange"}
},
Then if I just want to modify one of those states I was told that the following was a no-no:
this.state.name = "John Smith";
But rather I should use:
this.setState({name: "John Smith",
phone: this.state.phone,
location: this.state.location,
best-friend: this.state.best-friend,
favorite-color: this.state.favorite-color});
There must be a more efficient way to do this. Is there a shorthand way to change just one property of my state object in a way that is safe for react?
Actually, you do not have to specify all the values. Only the one you would like to have a new value for.
setState
will only add (or subsequently overwrite) values to your state. It will not re-create the whole object.
You can find the relevant documentation here. Facebook developers also thought about the exact same question you raised here and under the hood they keep the old values, and I'm quoting here:
The first argument can be an object (containing zero or more keys to update) or a function (of state and props) that returns an object containing keys to update.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With