onSnapshot方法出现问题。它不会等待第二次onsnapshot调用,因此返回的值不正确。在第二次onsnapshot调用中获取的用户,当值已经返回时,稍后将在控制台日志中显示。
如果您喜欢其他结构,欢迎提出任何解决方案和建议! 谢谢大家。
控制台日志:https://imgur.com/a/vhm61nu.png
export const FirebaseGetStrikeLists2 = async (houseId: string) => {
let strikes: StrikeListDocument[] = [];
firestore()
.collection(FirebaseConstraints.HouseCollection)
.doc(houseId)
.collection(FirebaseConstraints.StrikeSubCollection)
.onSnapshot(async x => {
x.forEach(async x => {
const strikeListDocument = x.data() as StrikeListDocument
strikeListDocument.users = []
strikeListDocument.id = x.id;
x.ref.collection(FirebaseConstraints.UserCollection).onSnapshot(
async x => {
let strikeListUsers: StrikeListDocumentUser[] = [];
x.forEach(async y => {
let userDocument = y.data() as StrikeListDocumentUser;
strikeListUsers.push(userDocument)
})
await Promise.all(strikeListUsers)
console.log('users found: ', strikeListUsers.length)
strikeListDocument.users = strikeListUsers
})
console.log('users set in array: ', strikeListDocument.users.length)
strikes.push(strikeListDocument)
})
})
return strikes;
}
我的Firestore结构如下: / houses / {HouseID} / strikelists / {StrikeListID} / users / {UserID}
编辑:
我让它在其他班级工作。首先,我尝试让代码等待,然后返回它,但找不到解决方案。所以我改变了我的结构。每当接收到数据时,它将更新状态(必须位于同一文件中)。我正在使用mobx作为可观察对象。
ps:也可以从UI组件调用此代码并将其更改为useState挂钩。
现在看起来像这样:
@observable private _strikeLists: StrikeListDocument[] | undefined;
export const firestoreStrikeListSubscription = (houseId: string) => {
firestore()
.collection(FirebaseConstraints.HouseCollection)
.doc(houseId)
.collection(FirebaseConstraints.StrikeSubCollection)
.onSnapshot(x => {
x.forEach(x => {
let strikeListDocument = x.data() as StrikeListDocument
strikeListDocument.id = x.id;
x.ref.collection(FirebaseConstraints.UserCollection).onSnapshot(
x => {
let strikeListDocumentUsers: StrikeListDocumentUser[] = []
x.forEach(y => {
let userDocument = y.data() as StrikeListDocumentUser;
strikeListDocumentUsers.push(userDocument)
})
const strikeList = this._strikeLists?.find(x => x.id == strikeListDocument.id)
if (strikeList)
strikeList.users = strikeListDocumentUsers
})
this._strikeLists?.push(strikeListDocument)
})
})
}
答案 0 :(得分:0)
<template>
返回onSnapshot()
。
请参见https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference#onsnapshot
您可以尝试以下代码吗?
void