问题
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