如何在 reactJS 中查看 firebase 存储桶文件夹中的所有图像

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

我想查看我的 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>
)

由于您要执行,并行未确定数量 异步[=25]调用=] 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);
 });