Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird setState usage [duplicate]

From React docs, I got confused by following use of setState. See this

 handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature}); // no key
  }

Where state is defined like

this.state = {temperature: '', scale: 'c'};

So instead of what I showed in the beginning I was expecting a call like this:

 handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature: temperature}); // with key
 }

What did I miss? (Apparently there is some automatic conversion taking place).

PS. temperature is just string not an object which you get from child component, e.g.

 handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }
like image 893
Giorgi Moniava Avatar asked Dec 11 '22 12:12

Giorgi Moniava


2 Answers

This is just syntactic sugar.

{scale: 'c', temperature} // key -> "temperature", value -> temperature 

is shorthand for

{scale: 'c', temperature: temperature} // key and value explicitly defined

This can be found on MDN (New notations in ECMAScript 2015).

like image 62
Tom Fenech Avatar answered Dec 31 '22 17:12

Tom Fenech


With es6, you can define an object property by variable like in the first example (Shorthand property names).

So temperature in your first example will be the key, and the value the variable is holding will be the, well, value.

More info on mdn

var a = 'foo', b = 42, c = {};
var o = {a, b, c};
console.log(o.a) // foo
like image 20
baao Avatar answered Dec 31 '22 15:12

baao