首页 > 解决方案 > 在 React Native 中显示嵌套对象数组中的所有数据

问题描述

这是我处于名为 childData 的状态的数据:{}

Object {
  "11-5-2019": Object {
    "18:32": Object {
      "color": "Brown",
      "time": "18:32",
    },
    "18:33": Object {
      "color": "Red",
      "time": "18:33",
    },
  },
}

我想在一页上显示所有这些数据。我尝试使用地图,但它给了我一个错误。我也试过一个平面列表。

{this.childData.map(item, index =>
<View key={index}>
    <Text>{item}</Text>
</View>
)}

但我不知道如何获取所有数据。我想在文本中有这样的数据:

11-05-2019
  18:32
    brown
    18:32
  18:33
    red
    18:33

标签: arraysreactjsreact-nativearraylistmultidimensional-array

解决方案


问题是,.map并且FlatList期待一个数组。您正在传递一个对象。所以首先你需要让你传递一个数组。

您可以使用lodash来做到这一点:

使用以下命令安装 lodash:

npm i --save lodash

然后将其用于:

var _ = require('lodash');

现在我们可以在渲染函数中转换你的数据:

render() {
   //get all keys, we pass them later 
   const keys = Object.keys(YOUR_DATA_OBJECTS);
   //here we are using lodah to create an array from all the objects
   const newData = _.values(YOUR_DATA_OBJECTS);
    return (
      <View style={styles.container}>
       <FlatList
        data={newData}
        renderItem={({item, index}) => this.renderItem(item, keys[index])}
       />
      </View>
    );
  }

现在我们有两个辅助渲染函数:

  renderSmallItems(item){
    console.log('small item', item);
    // iterate over objects, create a new View and return the result
    const arr = _.map(item, function(value, key) {
    return (
        <View key={key}>
          <Text> Color:  {value.color} </Text>
          <Text> Time:  {value.time} </Text>
        </View>
    );
  });
     return arr; 
  }
  renderItem(item, key) {
    return(
      <View style={{marginBottom: 15}}>
      <Text> Key: {key} </Text>
      {this.renderSmallItems(item)}
      </View>
    );
  }

输出:

演示图像

工作演示:

https://snack.expo.io/HyBSpYr2E


推荐阅读