我正在从我的 Firebase Cloud Firestore 获取的 .map 中创建帖子列表。我还有连接到每个帖子的照片,我使用 Cloud Storage 中的 post.title + '.jpg'
获取它们。帖子标题非常吸引人,但是当使用 fetchImage
时,它没有显示在帖子中。它显示在 console.log 中。我还可以从控制台访问该网址,所以没有任何问题。
有什么想法吗?
{this.state.posts.map((post, i) => {
let fetchImage
firebase
.storage()
.ref(post.title + '.jpg')
.getDownloadURL()
.then((url) => {
console.log(url)
fetchImage = url;
});
return (
<Text>{post.title}</Text>
<Image
style={styles.image}
source={{
uri: fetchImage
}}
/>
)}
)}
最佳答案
下载 URL 是异步加载的。要了解这意味着什么,请放置一些日志语句:
console.log("Before calling getDownloadURL")
firebase
.storage()
.ref(post.title + '.jpg')
.getDownloadURL()
.then((url) => {
console.log("Got URL")
});
console.log("After calling getDownloadURL")
当您运行此代码时,您会得到:
Before calling getDownloadURL
After calling getDownloadURL
Got URL
这可能不是您期望的输出顺序。但它完全解释了为什么您的 return
不返回下载 URL:尚未加载。
then()
您调用 getDownloadURL
的回调在您之后运行return
使用 uri: fetchImage
的组件。并且您无法返回尚未加载的值。
React 中的常见解决方案是存储异步加载到组件状态中的任何数据。
this.state.posts.map((post, i) => {
let fetchImage
firebase
.storage()
.ref(post.title + '.jpg')
.getDownloadURL()
.then((url) => {
let state = {};
state[post.title+"_url"] = url
this.setState(state)
});
})
自从调用setState()
以来强制组件重新渲染自身,然后新的渲染将从状态中获取更新的下载 URL。
return (
<Text>{post.title}</Text>
<Image
style={styles.image}
source={{
uri: this.state[post.title+"_url"]
}}
/>
关于javascript - 来自 Cloud Storage 的图像未在 .map 列表中重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52836115/