【问题标题】:Show all the data from a nested array of objects in React Native在 React Native 中显示嵌套对象数组中的所有数据
【发布时间】:2019-09-29 14:35:42
【问题描述】:

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

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

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

{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

【问题讨论】:

  • 我在下面回答了您的问题,如果您有任何问题,请随时提出。

标签: arrays reactjs react-native arraylist multidimensional-array


【解决方案1】:

问题是.mapFlatList 需要一个数组。您正在传递一个对象。所以首先你需要让你传递一个数组。

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    相关资源
    最近更新 更多