【发布时间】:2015-09-04 13:43:00
【问题描述】:
对 ES6 还是新手,所以试图理解为什么下面这两个函数之间存在差异。我正在使用 React 并注意到在编写设置状态的非 ES6 函数时出现错误。这发生在 componentDidMount 中。
这种方式在 ES6 中有效并返回我需要的内容:
(pos) => this.setState({
lat: pos.coords.latitude,
lng: pos.coords.longitude,
})
但是,这样会抛出一个错误——“Uncaught TypeError: this.setState is not a function”
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>
);
}
});
我们不胜感激。谢谢!
【问题讨论】:
-
正如@Andrey 指出的那样:
Arrow functions have implicit this binding所以带有(function(pos){...}).bind(this)的非箭头应该等同于箭头一
标签: javascript reactjs ecmascript-6