如何解决无法从openWeatherMap Api渲染weather [0] .main属性,它给出了未定义的错误?
我正在使用React Hooks和地理位置来获取经度和纬度,以便从OpenWeatherMap获取天气数据,现在我可以渲染weatherData.name属性,但是weatherData.weather[0].main
可以提供:
未定义的TypeError。
反应码
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
}
我缺少的是访问值有什么问题吗?
解决方法
使用前,您需要添加null
或undefined
支票。该API稍后会返回结果,因此最初您基于{}
有一个空对象useState({})
。
解决方案可能是:
<h1>
{
weatherData &&
weatherData.weather &&
weatherData.weather[0] &&
weatherData.weather[0].main
}
</h1>
或更短为weatherData.weather && weatherData.weather[0].main
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。