2017-01-02 46 views
0

我试图从Firebase存储中检索图片网址,然后使用该网址设置图片。然而,似乎是我设置的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); 
    }); 
} 

我把它从一个组件作出反应使用这样的功能:

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返回undefined,图像未正确加载。

我也用试图使测试仪内渲染()这样的:

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

而且我被记录表明该函数返回一个未定义的值别的反应。我怀疑它与Firebase的异步本质有关,但我不知道如何解决它。通过谷歌React-Native: Download Image from Firebase Storage

回答

1

发现这一点,并决定回答的情况下,别人嫌弃:

这个问题可能与。

您的示例不起作用,因为在承诺解决时,React不更新组件。这意味着您的图片网址仍为undefined

要解决此问题,您可以在承诺中调用this.setState()(或者如果您使用的是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> 
    ); 
    } 
} 

完全codepen: https://codepen.io/DeividasK/pen/pRmbWq