【发布时间】:2020-12-05 08:41:59
【问题描述】:
我试图从应用组件中的状态访问一个数组,但我不知道为什么它不起作用
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 另有说明
【问题讨论】:
标签: javascript html arrays reactjs api