来自 Cloud Storage 的图像未在 .map 列表中重新渲染 [英] Image from Cloud Storage is not redendring in .map list

查看:17
本文介绍了来自 Cloud Storage 的图像未在 .map 列表中重新渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从我的 Firebase Cloud Firestore 获取 .map 中的帖子列表.我也有连接到每个帖子的照片,我使用 post.title + '.jpg' 从云存储中获取它们.帖子标题很吸引人,但是当使用 fetchImage 时,它没有显示在帖子中.它显示在 console.log 中.我也可以从控制台访问 url,所以没有错.

I am making a list of posts in a .map fetching from my Firebase Cloud Firestore. I also have photos connecting to each post, and I fetch them by using the post.title + '.jpg' from Cloud Storage. The post title is fetching great, but when using the fetchImage it is not showing in the post. It is showing in the console.log. I can also access the url from the console, so nothing wrong there.

有什么想法吗?

{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 是异步加载的.要了解这意味着什么,请放置一些日志语句:

The download URL is loaded asynchronously. To see what this means, place a few log statements:

console.log("Before calling getDownloadURL")
firebase
.storage()
.ref(post.title + '.jpg')
.getDownloadURL()
.then((url) => {
  console.log("Got URL")
});
console.log("After calling getDownloadURL")

当您运行此代码时,您会得到:

When you run this code you get:

在调用 getDownloadURL 之前

Before calling getDownloadURL

调用 getDownloadURL 后

After calling getDownloadURL

获得网址

这可能不是您期望的输出顺序.但它完全解释了为什么您的 return 不返回下载 URL:它尚未加载.

This is probably not the order you expected the output in. But it completely explains why your return does not return the download URL: it hasn't been loaded yet.

从您调用 getDownloadURLthen() 回调返回使用<代码>uri:fetchImage.并且您不能返回尚未加载的值.

The then() callback from your call to getDownloadURL runs after you return the component that uses uri: fetchImage. And you can't return a value that hasn't loaded yet.

React 中常见的解决方案是存储异步加载到组件状态中的任何数据.

The common solution in React is to store any data that is asynchronously loaded into the component's state.

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.

Since any call to setState() forces the component to rerender itself, the new render will then pick up the updated download URL from the state.

return (
  <Text>{post.title}</Text>
  <Image
    style={styles.image}
    source={{
    uri: this.state[post.title+"_url"]
    }}
  />

这篇关于来自 Cloud Storage 的图像未在 .map 列表中重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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