我有一组用户ID,它们作为“成员”传递给getMemberAvatars()函数。我获取每个id,在用户集合中查找它们,然后将其photoURL放入一个名为memberAvatars的数组中。一旦有了该URLS数组,就可以使用map传递回JSX。但是,URLS的memberArray填充在回调中-因此我的JSX在返回之前会呈现。
我需要等待结果。也许异步/等待可以帮助?还有其他想法吗?
getMemberAvatars(members) {
let memberAvatars = [];
members.forEach(userId => {
db.collection("users")
.doc(userId)
.get()
.then(doc => {
memberAvatars.push(doc.data().photoURL);
});
});
return memberAvatars.map((url, index) => <Avatar src={url} />);
}
根据道格(Doug)在下面的评论,尝试此操作无济于事。...
getPhotos(members) {
let urls = [];
for (let userId in members) {
db.collection("users")
.doc(userId)
.get()
.then(doc => {
urls.push(doc.data().photoURL);
});
}
return urls;
}
async getMemberAvatars(members) {
let results = [];
let urls = await this.getPhotos(members);
await Promise.all(
urls.map(async url => {
results = await (<Avatar src={url} />);
})
);
return results;
}