Firebase storage: download images to and put to img src in React map

╄→尐↘猪︶ㄣ 提交于 2021-02-13 17:37:48

问题


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.


回答1:


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.

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.

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

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.



来源:https://stackoverflow.com/questions/61190939/firebase-storage-download-images-to-and-put-to-img-src-in-react-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!