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!