首页 > 解决方案 > 如何将图像从firebase加载到轮播反应?

问题描述

我正在尝试从加载到react-responsive-carousel的 firebase 存储中获取一些图像。问题是只有 1 或 2 个甚至没有加载图像(至少有 10 个图像)。这就是我正在尝试的:

const [imagenes, setImagenes] = useState([]);

useEffect(() => {
        const fetchedImagenes = [];

        firebase.storage().ref().child('PR/Gallery').listAll().then(function (result) {
            result.items.forEach(function (itemRef) {
                itemRef.getDownloadURL().then(function (link) {
                    const fetchedImagen = link
                    fetchedImagenes.push(fetchedImagen)
                })
            });
            setImagenes(fetchedImagenes)
        })

}, [])

这是carousel代码:

<Carousel dynamicHeight={true}>
    {imagenes.map(imagen => {
        return <div>
            <img src={imagen} />
        </div>
    })}
</Carousel>

我的猜测是imagenes当我显示图像时数组没有被填充,那么有什么方法可以等待imagenes数组被填充然后显示图像?

标签: reactjsfirebasefirebase-storage

解决方案


你现在在调用setImagenes(fetchedImagenes)任何一个之前fetchedImagenes.push(fetchedImagen)调用,所以你设置了一个空数组。

快速修复是通过将下载 URL 移动到then回调中来将数组设置为状态:

firebase.storage().ref().child('PR/Gallery').listAll().then(function (result) {
    result.items.forEach((itemRef) => {
        itemRef.getDownloadURL().then((link) => {
            const fetchedImagen = link
            fetchedImagenes.push(fetchedImagen)
            setImagenes(fetchedImagenes)
        })
    });
})

这将起作用,但在确定任何下载 URL 时更新 UI 时可能会导致一些闪烁。

如果您只想更新一次状态/用户界面,您正在寻找Promise.all,它会是这样的:

firebase.storage().ref().child('PR/Gallery').listAll().then(function (result) {
    const promises = result.items.map((itemRef) => itemRef.getDownloadURL());
    Promise.all(promises).then((urls) =>
        setImagenes(urls)
    });
})

推荐阅读