簡體   English   中英

如何查看 reactJS 中 firebase 存儲桶文件夾中的所有圖像

[英]How to View All Images from a firebase storage bucket folder in reactJS

我想查看 firebase 存儲桶中特定文件夾中所有上傳的圖像。

我設法獲得了文件夾中所有 URL 的列表,但是當我嘗試查看它們時,只顯示一張圖像,並且沒有顯示 rest。

我究竟做錯了什么?

這是我的代碼:

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

由於您要並行執行未確定數量異步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);
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM