{React Native} Async\Await not working properly with setSate

前端 未结 1 503
刺人心
刺人心 2021-01-21 10:49

Can someone help me understand what I am not doing correctly? Consider this simple code

 var images = []; 
 const [funImage, setFunImage] = useState([]);


//Som         


        
1条回答
  •  有刺的猬
    2021-01-21 11:50

    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);
    });
    

    0 讨论(0)
提交回复
热议问题