【问题标题】:Downloading image from Firebase (React Native)从 Firebase 下载图像(React Native)
【发布时间】:2021-03-08 23:32:55
【问题描述】:

我正在尝试从 Firebase Storage 下载图像并将其显示在我的应用中。我尝试获取下载网址的方式如下:

let imageRef = firebase.storage().ref('users/' + firebase.auth().currentUser.uid + '/' + 'userImage');
    imageRef
    .getDownloadURL()
    .then((url) => {
    console.log(url)
    })
    .catch((e) => console.log('getting downloadURL of image error => ', e));

现在,这会完美地注销 url。但是,无法从此功能之外访问它。如果我尝试在 .catch 之后立即访问它,我会收到以下错误:

ReferenceError:找不到变量:url

这当然意味着当我尝试以以下方式显示图像时,我无法调用 url:

<Image source={{uri: url}} />

关于如何处理和解决这个问题的任何想法?非常感谢!

【问题讨论】:

    标签: javascript reactjs firebase react-native firebase-storage


    【解决方案1】:

    解决方案是将 URL 存储在组件的状态中,而不是存储在变量中:

    let imageRef = firebase.storage().ref('users/' + firebase.auth().currentUser.uid + '/' + 'userImage');
        imageRef
        .getDownloadURL()
        .then((url) => {
          setState({ url: url });
        })
        .catch((e) => console.log('getting downloadURL of image error => ', e));
    

    这不仅可以确保渲染方法可以找到它,而且可以在计算完 URL 后重新渲染输出。


    如果你use hooks,你会有类似的东西:

    const [url, setUrl] = useState();
    
    let imageRef = firebase.storage().ref('users/' + firebase.auth().currentUser.uid + '/' + 'userImage');
        imageRef
        .getDownloadURL()
        .then((url) => {
          setUrl(url);
        })
        .catch((e) => console.log('getting downloadURL of image error => ', e));
    

    【讨论】:

    • 太棒了!非常感谢您的回答和善意的解释。
    猜你喜欢
    • 2017-01-16
    • 2021-06-12
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多