reactjs - ReactJS - TypeError:无法读取未定义的属性“0”
问题描述
我正在尝试制作一个天气应用程序来学习一些 ReactJS。
我在组件内部的一个方法中使用这个 fetch调用了OpenWeatherMap API 。componentDidMount
WeatherCard
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>
)
}
有谁知道我遇到的问题可能是什么?非常感谢!
解决方案
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>
)
}
推荐阅读
- c++ - 即使函数已经存在,C++ 未定义的函数引用错误
- java - admob SettingEnabled false
- typo3-9.x - 错字3 Bootstrap 包子导航左侧
- python - 如何将变量“s”传递给 is_fl_vowel() 方法?
- python - 使用 Django 和单个网页模板将网页内容存储在数据库中的最佳方式
- sql-server - 排除历史记录表中的列
- swiftui - 如何使用 SwiftUI 禁用/修改按钮?
- c# - 如何在 ASP.NET Core 中将没有文件名的多部分/表单数据文件绑定到 IFormFile
- c# - Asp.net Core Razor 页面从 _layout 发布
- reactjs - NPX create-react-app 找不到 @typescript-eslint/experimental-utils@2.19.1 的匹配版本