我想從我的 firebase 存盤桶中的特定檔案夾查看所有上傳的影像。
我設法獲取了檔案夾中所有 URL 的串列,但是當我嘗試查看它們時,只顯示一張影像,其余的未顯示。
我究竟做錯了什么?
這是我的代碼:
const [allRandomImages,setAllRandomImages] = useState([])
const images = []
const getRandomImages = () => {
const storageRef = storage.ref(`random/${AWB}`)
storageRef.listAll().then((result) => {
result.items.forEach((imageRef) => {
imageRef.getDownloadURL().then((url) => {
console.log(url);
images.push(url)
setAllRandomImages(images)
})
})
})
}
useEffect(() => {
getRandomImages()
},[]);
return (
<div>
<a><img id="packing" alt="" style={styles} /></a>
<a><img id="commercial" alt="" style={styles} /></a>
<a><img id="cof" alt="" style={styles} /></a>
<a><img id="otherdoc" alt="" style={styles} /></a>
{ allRandomImages.map((img, i) => (
<img src={img} />
))}
</div>
)
uj5u.com熱心網友回復:
由于要并行執行對異步方法的不確定次數的呼叫,因此可以使用如下(未經測驗): getDownloadURL()Promise.all()
storageRef.listAll()
.then((result) => {
const promises = [];
result.items.forEach((imageRef) => {
promises.push(imageRef.getDownloadURL());
});
return Promise.all(promises);
})
.then(urlsArray => {
setAllRandomImages(urlsArray);
});
您還可以使用map,如下所示:
storageRef.listAll()
.then((result) => {
return Promise.all(result.items.map(imageRef => imageRef.getDownloadURL());
})
.then(urlsArray => {
setAllRandomImages(urlsArray);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/370041.html
標籤:javascript 反应 火力基地 谷歌云存储 火力存储
