{React Native} Async\Await 与 setSate 无法正常工作

IT技术 reactjs firebase react-native google-cloud-firestore async-await
2021-05-01 00:40:26

有人可以帮助我了解我做错了什么吗?考虑这个简单的代码

 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 中的其余图像。

看看我正在运行的应用程序的这个GIF 和 setState 的问题

1个回答

该代码不起作用,因为您的 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);
});