我正在尝试使用我正在尝试从中提取数据的天气 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>