我还不太熟悉ES6,希望能理解下面这两个函数之间的区别。我正在使用React,并且注意到写一个非ES6函数来设置状态时会出现错误。这是在componentDidMount中发生的。
这种方式在ES6中可以工作并返回我所需要的:
(pos) => this.setState({
lat: pos.coords.latitude,
lng: pos.coords.longitude,
})
然而,这种方法会抛出一个错误 - “Uncaught TypeError: this.setState不是一个函数”。
function(pos) {
this.setState({
lat: pos.coords.latitude,
lng: pos.coords.longitude
})
}
这两个不是完全一样的东西吗?有人能解释一下为什么会出现这个错误吗?
以下是来自React类的代码,提供更多上下文信息:
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>
);
}
});
非常感谢您的帮助。谢谢!
(function(pos){...}).bind(this)
应该等同于箭头函数。 - birdspider