【问题标题】:Access nested array value inside other array in the stateful ReactJS component访问有状态 ReactJS 组件中其他数组内的嵌套数组值
【发布时间】:2020-11-01 19:50:38
【问题描述】:

我正在尝试从假 Postman API 调用 react 应用程序中的数据,到目前为止,当我从单个对象数组调用时它运行良好:

{
   "animals": [
 {
      "id": 1,
      "name": "Tiger",
      "diet": "Carnivore",
      "habitant": "Asia",
      "lfespan": "1-15 years"
 },
  {
      "id": 2,
      "name": "Lion",
      "diet": "Carnivore",
      "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)
}

但是,当我尝试从以下类别调用数据时,我的数据没有显示在屏幕上:野猫、鸟类。我只是不知道该怎么做。我很确定这非常简单,但我是初学者,我无法在任何地方找到答案。我试图做的,但没有成功:

 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,
      "name": "Tiger",
      "diet": "Carnivore",
      "habitant": "Asia",
      "lfespan": "1-15 years"
    },
    {
      "id": 2,
      "name": "Lion",
      "diet": "Carnivore",
      "habitant": "Africa",
      "lfespan": "1-13 years"
    },
    {
      "id": 3,
      "name": "Leopard",
      "diet": "Carnivore",
      "habitant": "Africa, South America",
      "lfespan": "1-12 years"
    }
  ],
  "birds": [
    {
      "id": 4,
      "name": "Macaw",
      "diet": "Herbivore",
      "habitant": "South America",
      "lfespan": "1-70 years"
    },
   ]
  }
 ]
}

【问题讨论】:

  • 您是否仍想将 整个 animals 数组存储在状态中?您的 setState 可能会改变您的状态对象形状。
  • 你在getAnimal回调中使用animalName做什么?您获取动物/动物的预期结果是什么?目前尚不清楚您是尝试渲染嵌套数组数据,还是尝试基于嵌套数组数据发出获取请求。请包含Minimal, Complete, and Reproducible 代码示例,请包含整个组件代码。

标签: javascript arrays json reactjs object


【解决方案1】:

试试这个,因为data.animals是一个data.animalsArray,你应该得到带有索引的数据。

 const data = await api_call.json();
 this.setState({ animals: data.animals[0].wildCats });

 or 
 this.setState({ animals: data.animals[0].birds });

【讨论】:

  • 那么消灭任何其他现有的动物类别?我认为这不是 OP 所要求的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 2016-07-23
  • 2017-01-11
  • 2019-03-27
  • 1970-01-01
  • 2020-07-03
相关资源
最近更新 更多