![](/img/trans.png)
[英]Uncaught TypeError: Cannot read property 'setState' of undefined
[英]ReactJS: Uncaught TypeError: Cannot read property 'setState' of undefined
我目前正在嘗試在reactJS(freecodecamp的一個)中構建一個小型氣象應用程序
當前,我得到以下錯誤:“未捕獲的TypeError:無法讀取未定義的屬性'setState'”
這是Codepen的鏈接: http ://codepen.io/rasmus/pen/aNGRJm
這是我猜是問題的代碼:
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})
}
});
})
}
},
網址不是問題。 我可以將接收到的數據記錄到控制台。
我想這是因為范圍的this
..
有任何想法嗎?
編輯:我不認為這是重復的,因為我只使用箭頭函數,並且它們使.bind(this)
過時
不是從函數內部調用ajax函數中的回調,因此this
並不指向您期望的內容,即您的類。
保存參考並從那里使用:
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})
}
});
})
}
},
嘗試在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})
}
});
})
}
}
您需要在該API調用之外緩存對此的引用。 箭頭函數為您綁定了此函數,因此您可以在函數中訪問它,它仍將指向組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.