从 Firebase 存储加载图片以进行反应

Mic*_*Lai 5 javascript firebase reactjs firebase-storage

我正在尝试从 Firebase Storage 检索图像 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);
    });
}
Run Code Online (Sandbox Code Playgroud)

我从使用如下函数的 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}
        />
    );
}
Run Code Online (Sandbox Code Playgroud)

图像未正确加载,因为 ProfilePictureUrl 返回 undefined。

我还尝试在 render() 中制作一个测试器,如下所示:

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

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

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

Dei*_*kas 4

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

您的示例不起作用,因为 React 在承诺解析时不会更新组件。这意味着您的图像 URL 仍然存在undefined

要解决这个问题,您可以调用this.setState()Promise(或者如果您使用 Flux / Redux 则分派一个操作)。这将自动使用新 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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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