繁体   English   中英

我正在尝试使用天气api,我正在尝试从中获取数据但未定义但属性确实存在

[英]I am trying to use a weather api that I am trying to pull data from i am getting undefined but the property does exist

我正在尝试渲染一些api数据,但这给了我一个错误

Cannot read property 'description' of undefined

我期望weatherData.weather.description给我一个像这样的字符串

"broken clouds"

我知道它在那里! 当我记录weatherData.weather时

[{…}]
0: {id: 803, main: "Clouds", description: "broken clouds", icon: "04n"}
length: 1
__proto__: Array(0)

现在说这是一个数组,但是当我尝试

console.log(weatherData.weather[0].description)

我仍然在上面得到同样的错误

这是我的代码

import axios from "axios";
import "./weather.css";
function Weather({user}){
    const [weatherData, setWeatherData] = useState([]);
    const openWeatherApi = `http://api.openweathermap.org/data/2.5/weather?q=${user.city},us&APPID=${user.apiKey}`;
    useEffect( () => {
        //axios get weather API\\

        axios.get(openWeatherApi)
        .then((response) => {
          setWeatherData(response.data);

        })
      },[])
    return(
        <>
            {console.log(typeof weatherData.weather)} {/* logs object*/ }
            {console.log(weatherData.weather.description)} {/* Cannot read property 'description' of undefined*/ }
            <div className="weather-box">
            <h1 className="weather-city">{weatherData.name}</h1>
            <p className="weather-description"></p>
            </div>

        </>
    )
}

export default Weather;

Axios调用是异步函数,而当weatherData为空数组时,模板将立即呈现。 因此,您尝试从空数组中的第一个元素访问description属性,这就是为什么会出现错误。

如果将这段代码放入模板中,则应该能够看到请求的数据。

<h1>{weatherData.length !== 0 ? weatherData.weather[0].description : 'fatching data...'}</h1>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM