繁体   English   中英

在React Native中使用axios.get访问数组列表中的数据

[英]Accessing data in an array List using axios.get in React Native

如何使用axios React Native在数组中创建访问数据以及按类别分隔的列表

我正在尝试在React Native中使用axio部署包含类别和产品的列表

我的json结构

  [
      {
        "id": "1",
        "name": "TV",
        "list": [
          {
            "idp": "1",
            "namep": "TV 43"
          },
          {
            "idp": "2",
            "namep": "TV 32"
          }
        ]
      },
      {
        "id": "2",
        "name": "Couch",
        "list": [
          {
            "idp": "3",
            "namep": "Couch for 3 people"
          },
          {
            "idp": "4",
            "namep": "Couch for 2 people"
          }
        ]
      }
    ]

我已经完成的工作,所以我可以显示类别

    constructor(props) {
       super(props);
       this.state = { category: [], list: [] };
       }

    componentWillMount() {
                axios.get('http://localhost/api/list.json')
               .then(response => {
                 this.setState({ 

             category: response.data, 
             list: response.data.list });

             })
               .catch(() => { console.log('Err'); });
           } 
.............

{this.state.category.map((item, i) => {
<Text>{item.name}</Text>
  { item.list.map((product, i) => {
       <Text>{product.namep}</Text>
  })}
 })}

范例清单

抱歉,我无法为您提供更详细,更集中的答案,因为我不熟悉react native,但是逻辑如下:

一个循环遍历主数组并提取类别名称,然后在其中循环另一个遍历乘积。

 const arr = [ { "id": "1", "name": "TV", "list": [ { "idp": "1", "namep": "TV 43" }, { "idp": "2", "namep": "TV 32" } ] }, { "id": "2", "name": "Couch", "list": [ { "idp": "3", "namep": "Couch for 3 people" }, { "idp": "4", "namep": "Couch for 2 people" } ] } ]; const parentEl = document.querySelector('#list'); arr.forEach((cat) => { const catEl = document.createElement('div') catEl.textContent = cat.name parentEl.append(catEl) cat.list.forEach((prod) => { const listEl = document.createElement('ul') const listItem = document.createElement('li') listItem.textContent = prod.namep listEl.append(listItem) parentEl.append(listEl) }) }) 
 <div id="list"> </div> 

因此,不知道本机反应,并假设您粘贴的这段代码是正确的,我冒风险说它会像这样:

{
  this.state.category.forEach((item, i) => {
    <Text>{item.name}</Text>
    item.list.forEach((product, i) => {
      <Text>{product.namep}</Text>
    })
  })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM