javascript - TypeError:无法读取 React 未定义的属性“标题”
问题描述
我试图从应用程序组件中的状态访问数组,但我不知道为什么它不起作用
import React from "react";
import "./App.css";
//import Category from "./components/Category";
class App extends React.Component {
constructor() {
super();
this.state = {
categories: [],
};
}
componentDidMount() {
//const addon = Math.floor(Math.random() * 1000);
fetch("http://jservice.io/api/categories?count=5")
.then((response) => response.json())
.then((data) => {
var arr = [];
for (var x in data) {
console.log(arr.push(data[x]));
console.log(data[x]);
}
this.setState({
categories: arr,
});
});
}
render() {
return <div>{this.state.categories[0].title}</div>;
}
}
export default App;
对于上下文,这是我从 API 获得的 JSON
[{"id":11531,"title":"mixed bag","clues_count":5},{"id":11532,"title":"let's \"ch\"at","clues_count":5},{"id":5412,"title":"prehistoric times","clues_count":10},{"id":11496,"title":"acting families","clues_count":5},{"id":11498,"title":"world city walk","clues_count":5}]
似乎每个对象都应该有一个标题,但 js 另有说明
解决方案
当应用程序第一次加载时,它还没有来自 API 的内容,因此您尝试访问空数组的第一个元素。因此,即使 API 调用很快,也总会有一种状态是该categories
数组为空。所以在render
方法中,你需要检查数组是否有一些值。
render() {
if (this.state.categories.length === 0) {
return <div>No categories</div>
}
return <div>{this.state.categories[0].title}</div>;
}
推荐阅读
- angular - Angular 8:对对象执行乘法时出现编译错误
- php - PHP "auto_prepend_file" 导致每个文件(包括不存在的文件)的 HTTP 200 响应
- r - str_replace_all() 不会检测返回或换行“\\r\\n”
- vba - 将长时间戳转换为更短的时间戳?
- pandas - 使用 BeautifulSoup 抓取数据而不是获取所有行
- python - Django - 自动将对象 ID 的副本保存到第二个表
- asp.net-core - Vue中的axios授权请求失败
- python - 迭代生成器函数的问题
- linux - 确定优先级并杀死它们
- swift - Swift - 当应用程序移动到后台时调用 viewDidLoad