[英]ReactJS: Uncaught TypeError: Cannot read property 'setState' of undefined
I'm currently trying to build a small weather app in reactJS (the one for freecodecamp) 我目前正在尝试在reactJS(freecodecamp的一个)中构建一个小型气象应用程序
currently I'm getting the error: "Uncaught TypeError: Cannot read property 'setState' of undefined" 当前,我得到以下错误:“未捕获的TypeError:无法读取未定义的属性'setState'”
here is a link to the codepen: http://codepen.io/rasmus/pen/aNGRJm 这是Codepen的链接: http ://codepen.io/rasmus/pen/aNGRJm
and here is the code that's the problem I guess: 这是我猜是问题的代码:
componentDidMount: () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
$.ajax({
url: URL + "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&APPID=" + APIKEY,
success: (data) => {
this.setState({data: data})
}
});
})
}
},
the url is not the problem. 网址不是问题。 I can log the data I'm receiving to the console.
我可以将接收到的数据记录到控制台。
I guess it's because of the scope of this
.. 我想这是因为范围的
this
..
any ideas? 有任何想法吗?
EDIT: I don't think that this is a duplicate because I'm only using arrow functions and they are making .bind(this)
obsolete 编辑:我不认为这是重复的,因为我只使用箭头函数,并且它们使
.bind(this)
过时
The callback in your ajax function is called not from within your function, so the this
is not pointing to what you expect, ie, your class. 不是从函数内部调用ajax函数中的回调,因此
this
并不指向您期望的内容,即您的类。
Save a reference and use it from there: 保存参考并从那里使用:
componentDidMount: () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let self = this;
$.ajax({
url: URL + "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&APPID=" + APIKEY,
success: (data) => {
self.setState({data: data})
}
});
})
}
},
Try to use arrow function like follows in componentDidMount: 尝试在componentDidMount中使用如下箭头功能:
componentDidMount = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let self = this;
$.ajax({
url: URL + "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&APPID=" + APIKEY,
success: (data) => {
self.setState({data: data})
}
});
})
}
}
You need to cache the reference to this outside of that API call. 您需要在该API调用之外缓存对此的引用。 The arrow function binds this for you so you can access it within the function and it will still point to the component.
箭头函数为您绑定了此函数,因此您可以在函数中访问它,它仍将指向组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.