简体   繁体   English

如何在React Native中循环遍历嵌套数组

[英]How to loop through nested arrays in React Native

I have an API which has nested objects, and within that nested arrays. 我有一个具有嵌套对象的API,并且在该嵌套数组中。 I have managed to display some data on the screen with .map, i have hard coded the first row. 我设法用.map在屏幕上显示了一些数据,我已经硬编码了第一行。 How to a do a nested map in React Native? 在React Native中如何做一个嵌套地图?

I have tried various solutions on stackoverflow but so far have not found any that have matched my solution 我已经尝试过各种关于stackoverflow的解决方案,但是到目前为止,还没有找到与我的解决方案匹配的解决方案

This is an example of my API and Code 这是我的API和代码的示例

{  
   "Name":"Worcestershire Acute Hospitals",
   "Sites":[  
      {  
         "SiteCode":"ALX",
         "Statistics":[  
            {  
               "Id":3,
               "Name":"Last Updated",
               "Value":"29 Jul 2019 18:26:39:487",
               "LastUpdated":"2019-07-29T18:32:16.833",
               "ImageURL":"Ambulance"
            },
            {  
               "Id":4,
               "Name":"Safety Level",
               "Value":"Overwhelmed",
               "LastUpdated":"2019-07-29T18:32:16.833",
               "ImageURL":"Ambulance"
            },
            {  
               "Id":5,
               "Name":"Todays Admissions",
               "Value":"32",
               "LastUpdated":"2019-07-29T18:32:16.833",
               "ImageURL":"Ambulance"
            },


  componentDidMount() {
    axios.get('http://ralxwebdev01/tod/api/tod')
.then(response => this.setState({ WrhDatas: response.data.Sites[0].Statistics }));
  }

  renderWrhName() {
    return this.state.WrhDatas.map(wrh => <Text key={wrh.Id}>{wrh.Name}</Text>);
  }


  render() {
    console.log(this.state.WrhDatas);
    return (
      <View>
      <Text>
      {this.renderWrhName()}
      </Text>
      </View>
    );
  }
}

I know for sites i am using [0] and the data displays on the screen. 我知道我正在使用[0]的网站,并且数据显示在屏幕上。 But I want to loop through sites, then loop through statistics. 但是我想遍历站点,然后遍历统计数据。

I want to loop through sites, then loop through statistics. 我想遍历站点,然后遍历统计数据。

In componentDidMount you can do this, componentDidMount您可以执行此操作,

this.setState({ WrhDatas: data.Sites.map(data => data.Statistics.map(stat=> stat)) },()=>console.log(this.state.WrhDatas));

This will return you the Array of Array's . 这将返回Array of Array's

And your renderWrhName function should be, 您的renderWrhName函数应该是

renderWrhName() {
    return this.state.WrhDatas.map(wrh => wrh.map(wrh => <div key={wrh.Id}>{wrh.Name}</div>));
}

Demo . 演示 (Tested with sample data provided in post) (使用后提供的示例数据进行了测试)

Note: For simplicity I have used div to render the data, but the same will work for Text . 注意:为简单起见,我使用div渲染数据,但是Text

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

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