簡體   English   中英

Firebase 存儲:將圖像下載到 React 中的 img src map

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

我正在嘗試 map 陣列從 Firebase 存儲中獲取圖像 url 並將它們列出到頁面。 該代碼給了我一個 url,但問題是代碼未按時將 url 設置為img變量並返回空的img變量。

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

我哪里做錯了? 也得到兩次結果。

調用getDownloadURL()意味着 SDK 必須調用服務器以獲取 URL。 當調用從服務器返回並下載 URL 時, <img src={img}早已運行。

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方法中加載數據:

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 將自動重新渲染依賴於修改后的 state 的 UI 部分。 因此,在您的渲染方法中,您將使用來自state.downloadURLs的下載 URL。

暫無
暫無

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

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