javascript - 从 Firebase 存储加载图片到 React

标签 javascript reactjs firebase firebase-storage

我正在尝试从 Firebase 存储中检索图像 url,然后使用该 url 设置图像。但是,似乎我正在使用当前代码将 src 设置为未定义的值:

这是我用来从 Firebase 存储中检索的函数

import {Firebase, 
        FirebaseAuth, 
        FirebaseDatabase, 
        FirebaseStorage} from '../Initialize'

export function getProfilePictureUrl(uid, callback, onErrorCallback) {
    var pathReference = FirebaseStorage.ref('profiles/' + uid + '/profilePicture.jpeg');

    pathReference.getDownloadURL().then((url) => {
        callback(url);
    }).catch((error) => {
        onErrorCallback(error);
    });
}

我从使用如下函数的 React 组件调用它:

render() {
    let profilePictureUrl = getProfilePictureUrl(uid, (url) => {
        console.log(url); // The console.log(url) returns a valid and working url for the image. So I know my imports are correct
        return url;
    },
    (error) => {
        console.log(error.code);
        return "";
    })
    return (
        <img
            src={profilePictureUrl}
        />
    );
}

图片未正确加载,因为 ProfilePictureUrl 返回未定义。

我也曾尝试在 render() 中创建一个测试器,如下所示:

render() {
     if(profilePictureUrl !== undefined) {
          console.log("defined");
     }
     else {
         console.log("undefined");
     }
     // returns 'undefined'
}

我正在记录 else 响应,表明该函数正在返回一个未定义的值。我怀疑它与 Firebase 的异步特性有关,但我不确定如何解决它。

这个问题可能与:React-Native: Download Image from Firebase Storage有关

最佳答案

通过谷歌找到这个并决定回答以防其他人也找到它。

您的示例不起作用,因为 React 不会在 promise 解析时更新组件。这意味着您的图像 URL 保持未定义

要解决此问题,您可以在 promise 中调用 this.setState()(如果您使用的是 flux/redux,则可以分派(dispatch)一个操作)。这将使用新 URL 自动为您更新状态。


代码示例

const config = {
  apiKey: "apiKey",
  authDomain: "authDomain",
  storageBucket: "bucketURL"
}

firebase.initializeApp(config)
const storage = firebase.storage().ref()

class HelloMessage extends React.Component {
  constructor () {
    super()
    this.state = {
      lithuania: '',
      uk: ''
    }

    this.getImage('lithuania')
    this.getImage('uk')
  }

  getImage (image) {
    storage.child(`${image}.png`).getDownloadURL().then((url) => {
      this.state[image] = url
      this.setState(this.state)
    })
  }

  render() {
    return (
      <div>
        Hello Lithuania<br />
        <img src={ this.state.lithuania } alt="Lithuanian flag" />
        <br />
        Hello United Kingdom<br />
        <img src={ this.state.uk } alt="UK flag" />
      </div>
    );
  }
}

完整代码笔: https://codepen.io/DeividasK/pen/pRmbWq

关于javascript - 从 Firebase 存储加载图片到 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421475/

相关文章:

reactjs - 如何在 reduxjs/toolkit React 和 Typescript 完成另一个 Action 时分派(dispatch)一个 Action ?

javascript - React JS : Filtering an array of objects by another array of objects. 如何顺序执行四个函数,包括。多次 API 调用

android - 检查用户是否在 Android 的 Firebase Google 身份验证中首次通过身份验证

javascript - 我的代码中的云功能错误或错误 : www. googleapis.com 网络超时。请再试一次

javascript - 在不单击任何按钮的情况下从 Web 使用 Flask 运行 python 脚本

javascript - 表单 onsubmit 不起作用结束更改输入值

reactjs - 历史上的 React Router RouteParams

reactjs - Firebase + Next.js 无服务器,在 GCP 上 - 如何管理暂存、生产 + 本地

javascript - 为什么 IsNaN(x) 与 x == NaN 不同,其中 x = NaN

javascript - 何时/为何在 for 循环上使用 map/reduce