在React Native中将多个Firestore集合合并到一个平面列表中



我在Firestore中有两个集合,我想在React Native中的一个平面列表中显示。

第一个集合如下:(这是由用户创建的(

collection_1 : [
{
id: a1b2c3,
name: 'joe'
}
{
id2: d4e5f6,
name: 'jane'
}
]

第二个集合看起来是这样的:(这是由朋友用户创建的(

collection_2: [
{
id: z9y8x7
userId: 'a1b2c3',
seenCount: 10,
},
{
id: w7v6u5
userId: 'd4e5f6'
seenCount: 5,
},
]

并且我想显示名称和看到的计数相邻的列表,条件是collection_1-id与collection_2userId:相同

joe (10)
jane (5)

但目前我的公寓里只有收藏品1:

<FlatList
data={collection_1}
keyExtractor={(item, index) => String(index)}
renderItem={({ item }) => (
<View>
<Text>
{item.name}
</Text>
</View>
)}
/> 

使用Flatlist有可能吗?或者有更好的方法吗?

您应该从两个集合列表中创建一个新数组。data就是您在以下示例中所需要的。

const collection1 = [
{
id: 'a1b2c3',
name: 'joe'
},
{
id: 'd4e5f6',
name: 'jane'
}
];
const collection2 = [
{
id: 'z9y8x7',
userId: 'a1b2c3',
seenCount: 10
},
{
id: 'w7v6u5',
userId: 'd4e5f6',
seenCount: 5
},
{
id: 'o1j3o2',
userId: 'd4e5f6',
seenCount: 7
}
];
const seenCounts = {};
collection2.forEach((item) => {
if (seenCounts[item.userId]) {
seenCounts[item.userId] += item.seenCount;
} else {
seenCounts[item.userId] = item.seenCount;
}
});
const data = collection1.map((item) => ({
...item,
seenCount: seenCounts[item.id]
}));
console.log(data);

您需要组合数组,以便您的对象由名称和屏幕组成(请运行snippet(。

然后你可以这样做。

<FlatList
data={final}  //this is the combined array
keyExtractor={(item, index) => String(index)}
renderItem={({ item }) => (
<View>
<Text>
{item.name} ({item.seenCount})
</Text>
</View>
)}
/> 

联合阵列

let collection_1 = [{
id: 'a1b2c3',
name: 'joe'
},
{
id: 'd4e5f6',
name: 'jane'
}
]

let collection_2 = [{
id: 'z9y8x7',
userId: 'a1b2c3',
seenCount: 10,
},
{
id: 'w7v6u5',
userId: 'd4e5f6',
seenCount: 5,
}
]
let final = collection_2.map(user => {
let name = collection_1.filter((users) => users.id === user.userId)[0].name
return { ...user,
name
}

})
console.log('final', final)

最新更新