Невозможно прочитать свойство 'email' из null с облачным хранилищем Firebase и аутентификацией. сохранение картинки в качестве имени пользователя - PullRequest
0 голосов
/ 01 мая 2020

Я создал хранилище в firbase хранилище изображений от пользователей, вошедших в систему, которые сохраняются в виде электронной почты в папке «profile-images».

Когда я пытаюсь извлечь изображения, firebase говорит, что адрес электронной почты не может прочитать адрес электронной почты свойства null.

Вот мой код:

import React, { Component } from 'react'


export class AccountPage extends Component {


//the upload of image to firebase cloud storage (works fine)
  Upload = (e) => {   
    let file = e.target.files[0];   
    let storageRef = firebase
    .storage()
    .ref("profile-images/" +firebase.auth().currentUser.email);

    let task = storageRef.put(file);
  }

//storage of the url, no problem stated.
    constructor(props) {
        super(props)

        this.state = {
             download: null,
        }

      }


//always says "cannot read property email of null" even with the if statement

componentDidMount(){
    if (firebase.auth().currentUser.email != null)
    {

//to define storageRef        
    let storageRef =  firebase
    .storage()
    .ref("profile-images/" +firebase.auth().currentUser.email);

    //location of the highlighted problem,
    storageRef.getDownloadURL().then(function(url) {
    this.setState({
       download:url
    });     
    console.log(url)       
    })
  }
  //end of problem's location

}

//the upload file input and the image to be displayed location
    render() {
        return (
            <div>
         <img src={this.state.download} height="42" width="42"/>

    <input type="file" onChange={this.Upload}/>

            </div>
        )
    }
}

export default AccountPage

Любые предложения о том, как действовать, приветствуются, и спасибо, что нашли время взглянуть на это.

1 Ответ

0 голосов
/ 01 мая 2020

Это означает, что firebase.auth().currentUser является нулевым при первом монтировании компонента.

Вы можете попробовать что-то вроде

componentDidMount(){
  if (firebase.auth().currentUser && firebase.auth().currentUser.email)
  // do the other stuff

, но если он не стреляет, то вам, вероятно, придется ловить его с помощью componentDidUpdate

 constructor(props) {
   super(props)
   this.state = {
     download: null,
     loginCheck: false,
   }
 }

componentDidUpdate(prevProps){
  if (!prevProps.loginCheck && firebase.auth().currentUser) {
    setState({ loginCheck: true });
    // do the other stuff

В качестве альтернативы вы передать firebase.auth().currentUser в качестве реквизита от родительского компонента и использовать его вместо этого.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...