Javascript 无法呈现天气[0]。openWeatherMap Api中的main属性,它给出了一个“取消定义”错误?
我正在使用React Hooks和geolocation从OpenWeatherMap获取天气数据的经度和纬度,现在我可以呈现weatherData.name属性,但是Javascript 无法呈现天气[0]。openWeatherMap Api中的main属性,它给出了一个“取消定义”错误?,javascript,reactjs,react-hooks,openweathermap,Javascript,Reactjs,React Hooks,Openweathermap,我正在使用React Hooks和geolocation从OpenWeatherMap获取天气数据的经度和纬度,现在我可以呈现weatherData.name属性,但是weatherData.weather[0]。main提供: 未定义的类型错误 反应码 import React, { useState, useEffect } from 'react'; const API_KEY = 'e683d9ae190fbf9ecf7a63c274ee7146'; function SearchW
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;
我缺少什么?访问值时是否有问题?在使用该值之前,您需要添加
null
或undefined
检查。API稍后返回结果,因此根据useState({})
,最初有一个空对象作为{}
解决办法可以是:
<h1>
{
weatherData &&
weatherData.weather &&
weatherData.weather[0] &&
weatherData.weather[0].main
}
</h1>
{
气象数据&&
天气数据&&
weatherData.weather[0]&&
weatherData.weather[0]。main
}
甚至更短,如
weatherData.weather&&weatherData.weather[0]。main
尝试weatherData.weather&&weatherData.weather[0]。main
。因为在运行时,值仍在加载。是的,得到了,谢谢!!
{
"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
}
<h1>
{
weatherData &&
weatherData.weather &&
weatherData.weather[0] &&
weatherData.weather[0].main
}
</h1>