首页 > 解决方案 > ReactJS - TypeError:无法读取未定义的属性“0”

问题描述

我正在尝试制作一个天气应用程序来学习一些 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
        })
    })
}

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

在此处输入图像描述

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

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

...我像这样访问它:

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

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

render() {
    return (
        <div>
            {this.state.weatherData.weather[0].main}
        </div>
    )
}

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

标签: reactjs

解决方案


On the first render the request has not yet started, and therefore there is no data yet, you need to have a loading boolean or just check if the data is already loaded before trying to access it.

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

    return (
        <div>
            {this.state.weatherData.weather[0].main}
        </div>
    )
}

推荐阅读