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);
}
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).
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
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