我正在使用 React Hooks 和地理定位来获取经度和纬度,以便从 OpenWeatherMap 获取天气数据,现在我可以渲染 weatherData.name 属性,但weatherData.weather[0].main给出:
未定义的类型错误。
反应代码
import React, { useState, useEffect } from 'react';
const API_KEY = 'e683d9ae190fbf9ecf7a63c274ee7146';
function SearchWeather() {
const [weatherData, setWeatherData] = useState({})
function getLonLat(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const lon = position.coords.longitude;
const lat = position.coords.latitude;
fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`)
.then(response => response.json())
.then(result => {
setWeatherData(result)
})
.catch(err => console.log(err));
})
}
}
useEffect(() => getLonLat())
return (
<div>
<h1>{weatherData.name}</h1>
<h1>{weatherData.weather[0].main}</h1>
</div>
)
}
export default SearchWeather;
错误信息
TypeError: weatherData.weather is undefined
SearchWeather
H:/React App/weather-app/w-app/src/components/SearchWeather.js:32
29 | return (
30 | <div>
31 | <h1>{weatherData.name}</h1>
> 32 | <h1>{weatherData.weather[0].main}</h1>
33 | </div>
34 | )
35 | }
OpenWeatherMap 结果数据
{
"coord": {
"lon": 91.81,
"lat": 26.14
},
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "50d"
}
],
"base": "stations",
"main": {
"temp": 307.15,
"feels_like": 313.68,
"temp_min": 307.15,
"temp_max": 307.15,
"pressure": 1004,
"humidity": 71
},
"visibility": 5000,
"wind": {
"speed": 2.7,
"deg": 274
},
"clouds": {
"all": 75
},
"dt": 1598513732,
"sys": {
"type": 1,
"id": 9117,
"country": "IN",
"sunrise": 1598484652,
"sunset": 1598530686
},
"timezone": 19800,
"id": 1272508,
"name": "Dispur",
"cod": 200
}
我错过了什么访问该值有什么问题吗?