有人可以帮助我了解我做错了什么吗?考虑这个简单的代码
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);。
setFunImage(images);
images.push(result);
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中拥有的其余图像。
funImage
看看我正在运行的应用的GIF以及setState的问题
该代码不起作用,因为您的forEach正在运行异步代码。这意味着它将在您设置图像后完成运行。这是一个修正了注释的解释-
// No need for images array outside const [funImage, setFunImage] = useState([]); ... firebase.firestore().collection('PostedFunActivities').where("location", "==" , place).get().then(async (querySnapshot) =>{ // instead of foreach, using map to aggregate the created promises into one array // Promise.all takes an array of promises and resolves after all of them completed running // returns an array with the promise results const images = await Promise.all(querySnapshot.map(async(doc) =>{ const ref = firebase.storage().ref('images/'+ doc.data().image) const result = await ref.getDownloadURL(); return result; })); setFunImage(images); });