Reactjs 从API返回JS数据
大家好,当我在ReactJS中运行此代码时Reactjs 从API返回JS数据,reactjs,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) } 我可以访问console.log(weather.data)但是当我尝
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:cannotreadproperty'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)
如果(数据)
weather
是一个数组,则其工作原理类似于,因此weather。数据
是未定义的
在weather
状态对象中没有显示数据
属性。还请包括一个代码示例。我们不知道您在哪里尝试控制台logweather.data..main
。