ES6还是个新手,所以试图理解下面这两个函数之间存在差异的原因。我正在使用React,并且注意到在编写设置状态的非ES6函数时出现错误。这发生在componentDidMount中。这个ES6箭头函数和常规函数的区别?
这样在ES6工作并返回我需要什么:
(pos) => this.setState({
lat: pos.coords.latitude,
lng: pos.coords.longitude,
})
然而,这种方式会引发错误 - “遗漏的类型错误:this.setState是不是一个函数”
function(pos) {
this.setState({
lat: pos.coords.latitude,
lng: pos.coords.longitude
})
}
这些不完全一样吗?任何人都可以解释为什么它会抛出这个错误?
下面是代码从反应类,以提供更多的上下文:
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>
);
}
});
任何和所有的帮助表示赞赏。谢谢!
'的console.log (this)' – Andreas
as @Andrey指出:'箭头函数隐含了这个绑定',所以带有'(function(pos){...})。bind(this)'的非箭头应该等同于箭头1 – birdspider