ReactJS - TypeError:无法读取未定义的属性“0”

Stu*_*t22 3 reactjs

我正在尝试制作一个天气应用程序以学习一些 ReactJS。

我在组件内部的一个方法中使用此 fetch调用了OpenWeatherMap API 。componentDidMountWeatherCard

constructor() {
    super()
    this.state = {
        weatherData: {}
    }
}

componentDidMount() {
    fetch('//api.openweathermap.org/data/2.5/weather?q=Calgary,ca&APPID=XXX')
    .then(response => response.json())
    .then(data => {
        this.setState({
            weatherData: data
        })
    })
}
Run Code Online (Sandbox Code Playgroud)

这是上述调用的示例 JSON 输出(给定有效的 API 密钥):

在此处输入图片说明

每当我想访问天气属性时,都会收到此错误消息:

类型错误:无法读取未定义的属性“0”

...我像这样访问它:

this.state.weatherData.weather[0].main

如果它有助于解决问题,这也是我的渲染方法:

render() {
    return (
        <div>
            {this.state.weatherData.weather[0].main}
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

有谁知道我遇到的问题可能是什么?非常感谢!

Can*_*tro 5

在第一次渲染时,请求还没有开始,因此还没有数据,你需要有一个加载布尔值,或者在尝试访问之前检查数据是否已经加载。

render() {
    if (!this.state.weatherData.weather) {
        return <span>Loading...</span>;
    }

    return (
        <div>
            {this.state.weatherData.weather[0].main}
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)