簡體   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