![](/img/trans.png)
[英]React - Uncaught TypeError: Cannot read properties of undefined (reading 'setState')
[英]React: Uncaught TypeError: Cannot read properties of undefined (reading 'setState')
我是學習 React 的新手,我想通過 API 調用來獲取一些東西,這似乎對我不起作用。 對於以下代碼,我在標題中提到的控制台中遇到錯誤。
該錯誤顯示在以下代碼的 fetch 語句中,我無法糾正它。 我在這里所做的是獲取 position 的緯度和經度並將其傳遞給 URL 以獲取天氣。
從“反應”導入反應,{組件}
class WeatherData extends Component{
constructor(props){
super(props);
this.state ={
weatherReport:[]
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(function(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
fetch('https://api.openweathermap.org/data/2.5/weather?lat='+{lat}+'&lon='+{lon}+'&appid=xxxxxxxxxxxxxxxxxxxxxxx')
.then(response => response.json())
.then(data => this.setState({ weatherReport: data.main}));
});
}
render(){
const { weatherReport } = this.state;
return(
<div>
{weatherReport.temp}
</div>
);
}
}
export default WeatherData;
任何幫助將不勝感激。
You are using a function using the function
keyword when getting the geolocation - this gives a new this
reference to anything inside its scope, including the arrow function and its contents. 使用粗箭頭 function 將當前this
綁定到其子塊,以在使用回調時保持正確的 scope。
此外,不知道你為什么在 url 中鏈接 object 像這樣:
componentDidMount() {
navigator.geolocation.getCurrentPosition((position) => { // this line
const lat = position.coords.latitude;
const lon = position.coords.longitude;
fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=xxxxxxxxxxxxxxxxxxxxxxx`
.then(response => response.json())
.then(data => this.setState({
weatherReport: data.main
}));
});
}
這是由於使用function
關鍵字和“胖箭頭”語法 ( =>
) 之間的差異
function
關鍵字創建了一個新的“ this
上下文”,而粗箭頭繼承了父上下文。 換句話說,當您使用function
時, this
關鍵字的值在 function 內部變成了新的值,而使用=>
時,它與在 ZC1C425268E68385F1ABZA4 外部的值相同。
您可以在此處閱讀有關this
關鍵字的更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
更多關於function
和=>
之間的區別可以在這里找到:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
所以,而不是這樣寫:
getCurrentPosition(function(position) {
你應該這樣寫:
getCurrentPosition((position) => {
完整示例:
import React, { Component } from "react"
class WeatherData extends Component {
constructor(props) {
super(props);
this.state = {
weatherReport: []
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition((position) => { // <- this is what has changed
const lat = position.coords.latitude;
const lon = position.coords.longitude;
fetch('https://api.openweathermap.org/data/2.5/weather?lat=' + { lat } + '&lon=' + { lon } + '&appid=xxxxxxxxxxxxxxxxxxxxxxx')
.then(response => response.json())
.then(data => this.setState({ weatherReport: data.main }));
});
}
render() {
const { weatherReport } = this.state;
return (
<div>
{weatherReport.temp}
</div>
);
}
}
export default WeatherData;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.