问题描述
我正在尝试从伪造的Postman API调用react应用程序中的数据,到目前为止,当我从单个对象数组调用时,它仍然可以正常工作:
{
"animals": [
{
"id": 1,"name": "Tiger","diet": "Carnivore","habitant": "Asia","lfespan": "1-15 years"
},{
"id": 2,"name": "Lion","habitant": "Africa","lfespan": "1-15 years"
},]
}
App.js
class App extends React.Component {
state = {
animals: []
}
// arrow function - no need to bind
getAnimal = async (e) => {
const animalName = e.target.elements.animalName.value;
e.preventDefault();
const api_call = await fetch(`https://4ab06793-05d5-47b8-b3cb-
56c26a95e5d4.mock.pstmn.io/animals`)
const data = await api_call.json();
this.setState({animals: data.animals});
console.log(this.state.animals)
}
但是,当我尝试从以下类别调用数据时,屏幕上不会显示我的数据:wildCats,birds。我只是不知道该怎么做。我敢肯定这是非常容易的,但是我是一个初学者,在任何地方都找不到答案。我尝试做的事没有奏效:
App.js
class App extends React.Component {
state = {
animals: [
{
wildCats: []
}
]
}
// arrow function - no need to bind
getAnimal = async (e) => {
const animalName = e.target.elements.animalName.value;
e.preventDefault();
const api_call = await fetch(`https://4ab06793-05d5-47b8-b3cb-
56c26a95e5d4.mock.pstmn.io/animals`)
const data = await api_call.json();
this.setState({animals: data.animals.wildCats});
console.log(this.state.animals.wildCats)
}
JSON file
{
"animals": [
{
"wildCats": [
{
"id": 1,"lfespan": "1-15 years"
},"lfespan": "1-13 years"
},{
"id": 3,"name": "Leopard","habitant": "Africa,South America","lfespan": "1-12 years"
}
],"birds": [
{
"id": 4,"name": "Macaw","diet": "Herbivore","habitant": "South America","lfespan": "1-70 years"
},]
}
]
}
解决方法
尝试一下,因为data.animals
是data.animals Array
,所以应该使用索引获取数据。
const data = await api_call.json();
this.setState({ animals: data.animals[0].wildCats });
or
this.setState({ animals: data.animals[0].birds });