[英]ReactJS data from API
Hello guys when i'm running this code in ReactJS大家好,当我在 ReactJS 中运行这段代码时
const callApi = async () => {
const response = await axios.get('http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=mykey');
setWeather(response)
}
i can get to console.log(weather.data)
but when i try to get console.log(weather.data.main)
i get this error TypeError: Cannot read property 'main' of undefined
i tried to parse that data to JSON but that didnt work either.我可以访问
console.log(weather.data)
但是当我尝试获取console.log(weather.data.main)
我收到这个错误TypeError: Cannot read property 'main' of undefined
我试图将该数据解析为 JSON但这也不起作用。
Here you can see that this object has this property:在这里你可以看到这个对象有这个属性:
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04n"
}
],
"base": "stations",
"main": {
"temp": 12.43,
"feels_like": 7.81,
"temp_min": 11.67,
"temp_max": 13,
"pressure": 1010,
"humidity": 62
},
.....other items
}
Thank you for all answers.谢谢大家的回答。
Sometimes during the first render data isn't defined yet so use:有时在第一次渲染期间还没有定义数据,所以使用:
console.log(weather.data?.main)
and works like a if(data)
并且像
if(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.