Still new to ES6 so trying to understand why there's a difference between these two functions below. I'm working in React and am noticing that I'm getting an error when writing a non-ES6 function that sets state. This is happening within componentDidMount.
This way in ES6 works and returns what i need:
(pos) => this.setState({
lat: pos.coords.latitude,
lng: pos.coords.longitude,
})
However, to this way throws an error - "Uncaught TypeError: this.setState is not a function"
function(pos) {
this.setState({
lat: pos.coords.latitude,
lng: pos.coords.longitude
})
}
Aren't these the exact same thing? Can anyone explain why it would be throwing this error?
Here is the code from the react class to provide more context:
var GeolocationExample = React.createClass({
getInitialState: function() {
return {
lat: '',
lng: '',
};
},
componentDidMount: function() {
navigator.geolocation.getCurrentPosition(
// Where I'm placing each of the above mentioned functions,
(err) => alert(err.message),
);
},
render: function() {
return (
<View>
<Text>
<Text style={styles.title}>Initial position: </Text>
{this.state.lat}
</Text>
<Text>
<Text style={styles.title}>Current position: </Text>
{this.state.lng}
</Text>
</View>
);
}
});
Any and all help is appreciated. Thank you!
No they are not the same. Arrow functions are automatically bound to the context where they are created. That means that
(x) => this.stuff = x
is (mostly) equivalent to:
(function(x) {
return this.stuff = x;
}.bind(this))
Arrow functions will also preserve the arguments, super and new.target of the function inside which it is created.
Which means
(function a() {
const u = () => console.log(arguments);
u("whatever");
})("a args");
will print something like ["a args"].
See here for more information.
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