Firebase存储:将图像下载到React地图中并放入img src [英] Firebase storage: download images to and put to img src in React map

查看:46
本文介绍了Firebase存储:将图像下载到React地图中并放入img src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试映射数组以从Firebase存储中获取图像URL,并将其列出到页面中.该代码为我提供了一个url,但是问题是代码没有按时将url设置为 img 变量,并没有返回空的 img 变量.

I'm trying to map array to get image url from Firebase storage and list them to page. The code give me a url, but the problem is that code not set url to img variable on time and returning empty img variable.

return(
    <div>
        <Header />
        {this.state.loaded ? <Loading /> : null}
        <div>
            {this.state.productsArr.map((product, i) => {
                let img = '';
                storageRef.child(`images/${product.images[0]}`)
                                        .getDownloadURL()
                                        .then((url) => {
                                            img = url
                                            console.log('then img', img)
                                        })
                                        .catch((err) => console.log(err))
                console.log('result',img)

                return(
                    <div key={i}>
                        <div>
                            <div>
                                <img src={img}
                                    alt={product.category} 
                                />
                            </div>
                        </div>
                    </div>
                )
            })}
        </div>
        <Footer />
    </div>
)

我在哪里弄错了?还要获得两次结果.

Where I did mistake? Also get results twice.

推荐答案

调用 getDownloadURL()意味着SDK必须调用服务器才能获取该URL.到从服务器返回带有下载URL的呼叫时,< img src = {img} 已经运行很长时间了.

Calling getDownloadURL() means that the SDK has to call to the server to get that URL. By the time that call returns from the server with the download URL, the <img src={img} has long since run.

因此,您将要在状态中存储下载URL,然后在渲染方法中使用状态中的URL.

For this reason you'll want to store the download URL in the state, and then use the URL from the state in your render method.

通常,您将开始在 componentWillMount 方法中加载数据:

You'll typically start loading the data in your componentWillMount method:

componentWillMount() {
    let promises = this.state.productsArr.map((product, i) => {
        return storageRef.child(`images/${product.images[0]}`).getDownloadURL();
    });
    Promise.all(promises).then((downloadURLs) => {
        setState({ downloadURLs });
    });
}

当您调用 setState()时,React将自动重新渲染依赖于已修改状态的UI部件.因此,在您的呈现方法中,您将使用来自 state.downloadURLs 的下载URL.

When you call setState() React will automatically rerender the UI parts that are dependent on the modified state. So then in your rendering method you'd use the download URLs from state.downloadURLs.

这篇关于Firebase存储:将图像下载到React地图中并放入img src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆