arrays - 在 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
解决方案
问题是,.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>
);
}
输出:
工作演示:
推荐阅读
- javascript - 为单页应用中被点击的元素生成css选择器
- c++ - 如何在 C++ 中更改对象的动态数组的大小
- git - 使用 Github 中主分支的所有提交创建新分支
- database - 有没有办法存储 python 类,以便我可以根据属性搜索它们?
- javascript - 处理可能具有或不具有嵌套对象的对象的最有效方法是什么?
- python - 将 CSV 保存在文档文件夹中
- javascript - 在 MongoDB 中登录并保存会话后 - 会话未定义
- c# - ManifestEmbeddedFileProvider() 在 Windows 上抛出异常
- node.js - Firebase 功能 - 部署失败
- autohotkey - 使用 AHK ControlClick,找不到所需的行为