在 React Native 中显示嵌套对象数组中的所有数据

编程入门 行业动态 更新时间:2024-10-28 10:30:22
本文介绍了在 React Native 中显示嵌套对象数组中的所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

这是我在名为 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 07:59:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/881893.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   组中   对象   数据   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!