Is there an abbreviated way to setState () in React?

Suppose I initialize the state of a component as follows:

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 change one of these states, I was told that the following: no-no:

this.state.name = "John Smith";

But I have to 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 one property of my state object so that it is safe to react?

+4
source share
2 answers

Actually, you do not need to specify all the values. Only the one for which you would like to have a new meaning.

setStatewill add (or subsequently overwrite) values ​​to your state. It does not recreate the entire object.

. Facebook , , , :

( ) ( ), , .

+8

, React! , , . .

getInitialState: function() {
  return {
    name: "Bob Smith",
    phone: "555-555-5555",
    location: "San Francisco, CA",
  }
}

// Somewhere else...
this.setState({
  name: "John Smith",
})

this.state

{
  name: "John Smith",
  phone: "555-555-5555",
  location: "San Francisco, CA",
}
+2

All Articles