【问题标题】:Accessing data in an array List using axios.get in React Native在 React Native 中使用 axios.get 访问数组 List 中的数据
【发布时间】:2018-03-18 00:20:30
【问题描述】:

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

【问题讨论】:

  • “拆分列表”是什么意思?
  • 访问数组中的数据,并按类别分隔列表@Oxcarga

标签: javascript react-native axios


【解决方案1】:

抱歉,由于我不熟悉 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>

所以,不知道 react native 并且假设您粘贴的这段代码是正确的,我冒着风险说它会变成这样:

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

【讨论】:

  • 谢谢,我在 ReactNative 中调整了逻辑,效果很好。
猜你喜欢
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-17
  • 2018-09-17
  • 2017-07-09
相关资源
最近更新 更多