问题描述
当我在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)
}
我可以进入console.log(weather.data)
,但是当我尝试获得console.log(weather.data.main)
时
我收到此错误TypeError: Cannot read property 'main' of undefined
,我试图将数据解析为JSON,但也没有用。
{
"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
}
谢谢所有答案。
解决方法
有时尚未定义第一个渲染数据,因此请使用:
console.log(weather.data?.main)
就像if(data)