javascript - 来自 Cloud Storage 的图像未在 .map 列表中重新渲染

标签 javascript reactjs react-native google-cloud-storage firebase-storage

我正在从我的 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/

相关文章:

javascript - JS新手,有没有办法把这些圆圈变成菱形?

php - 将js值分配给php变量时出现问题

reactjs - 在 React Native 中提交表单

react-native - 如何在react native中输入确认码

javascript - 使用纯 JavaScript 获取表单中选中复选框的 ID

java - 无法使用Keycloak验证应用程序用户的登录

javascript - 使用 webpack 2.2.0 时 CSS 字体加载器出错

react-native - react native : use a variable string in the state like this : this. state.variableString

javascript - React Native,事件暂停时setInterval停止

javascript - 节点创建的 DOM 回调