如何使用 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> 
  })} 
 })} 

Example list

请您参考如下方法:

抱歉,我无法给您更详细和更有针对性的答案,因为我不熟悉 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>

因此,不知道 native react 并假设您粘贴的代码是正确的,我将冒险说它会是这样的:

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!