{React Native} Async \ Await无法与setSate一起正常使用 [英] {React Native} Async\Await not working properly with setSate
问题描述
有人可以帮助我了解我做错了什么吗? 考虑这个简单的代码
Can someone help me understand what I am not doing correctly? Consider this simple code
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);
完成之前将所有结果推入数组之前被执行.我以为等待会阻塞下面的其余代码
基本上,我要尝试执行的操作背后的概念是将所有结果推送到images
,然后调用setFunImage(images);
.
I am not understanding why setFunImage(images);
gets executed before images.push(result);
finishes to push all the results into the array. I thought await would block the remainder of the code below it
Basically the concept behind what I am trying to do is to have all my results pushed to images
and THEN call setFunImage(images);
.
我该如何实现?甚至有可能吗?
How can I achieve that? Is it even possible?
编辑
我更改了代码,希望找到解决方案,这是到目前为止的目标:
I changed my code in hope to find a solution to this and this is where I got to so far:
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中拥有的其余图像.
Interestingly enough, when this function executes funImage
is populated with 1 image, but then when I refresh it gets populated with the rest of my images that I have in my firebase.
推荐答案
该代码不起作用,因为您的forEach正在运行异步代码.这意味着它将在您设置图像后完成运行. 这是一个修正了注释的解释-
The code doesn't work because your forEach is running async code. Which means it will finish running after you set your images. Here's a fix with some explanations in comments -
// 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);
});
这篇关于{React Native} Async \ Await无法与setSate一起正常使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!