有人可以帮助我了解我做错了什么吗?考虑这个简单的代码
var images = [];
const [funImage, setFunImage] = useState([]);
//Some function that does this below
firebase.firestore().collection('PostedFunActivities').where("location", "==" , place).get().then((querySnapshot) =>{
querySnapshot.forEach(async(doc) =>{
const ref = firebase.storage().ref('images/'+ doc.data().image)
const result = await ref.getDownloadURL();
images.push(result);
})
setFunImage(images);
});
我不明白为什么setFunImage(images);
在images.push(result);
完成之前执行以将所有结果推送到数组中。我认为 await 会阻止它下面的其余代码 基本上我想要做的背后的概念是将我的所有结果推送到images
然后调用setFunImage(images);
.
我怎样才能做到这一点?甚至有可能吗?
编辑
我改变了我的代码,希望能找到解决方案,这是我到目前为止的目标:
firebase.firestore().collection('PostedFunActivities').where("location", "==" , place).get().then((querySnapshot) => {
querySnapshot.forEach(async(doc) => {
const ref = firebase.storage().ref('images/' + doc.data().image)
const result = await ref.getDownloadURL();
images.push(result);
setFunImage(...funImage,images);
})
});
有趣的是,当这个函数执行时funImage
填充了 1 个图像,但是当我刷新它时,它填充了我在我的 firebase 中的其余图像。