在 React Native 中显示嵌套对象数组中的所有数据 [英] Show all the data from a nested array of objects in React Native

查看:43
本文介绍了在 React Native 中显示嵌套对象数组中的所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在名为 childData 的状态下的数据:{}

对象{11-5-2019":对象{18:32":对象{"color": "棕色","时间": "18:32",},18:33":对象{红色","时间": "18:33",},},}

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

{this.childData.map(item, index =><查看键={index}><文本>{项目}</文本></查看>)}

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

11-05-201918:32棕色的18:3218:33红色的18:33

解决方案

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

您可以使用

工作演示:

https://snack.expo.io/HyBSpYr2E

This is my data in a state called childData: {}

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

I want to show all this data on one page. I've tried to use a map but it gives me an error. Also I have tried a FlatList.

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

But I don't know how to get all the data. I want to have the data like this in text:

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

解决方案

The problem is that .map and FlatList are expecting an array. You are passing an object. So first you need to make that you are passing an array.

You can do that by using lodash:

Install lodash with:

npm i --save lodash

and then use it with:

var _ = require('lodash');

Now we can transform your data within the render function :

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>
    );
  }

And now we have two helper render functions:

  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>
    );
  }

Output:

Working Demo:

https://snack.expo.io/HyBSpYr2E

这篇关于在 React Native 中显示嵌套对象数组中的所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆