2017-01-02 56 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