Null不是一个对象(正在评估'firebase.auth()。currentUser.email'):FIREBASE REACT NATIVE(EXPO)

问题描述 投票:0回答:1

我正在EXPO CLI的react native项目中使用firebase。我正在尝试在已登录的另一个文件中获取用户信息。但是由于某些原因,我遇到了this屏幕截图中显示的错误。

“”

我尝试在componentWillMount()和构造函数中初始化firebase对象。然而,它会抛出相同的错误,但是如果我回来并重新启动应用程序。它工作正常。Dashboard.js

import React, { Component } from 'react'
import { Text, View , StyleSheet } from 'react-native'
import * as firebase from 'firebase';
import firebaseConfig from '../config';
if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
  }
export class DashBoard extends Component {
    constructor()
    {
        super();  
    }
    render() {
            return (
                <View style={styles.container}>
                    <Text>Hello {firebase.auth().currentUser.email} </Text>
                </View>
            )
    }
}

export default DashBoard;

const styles= StyleSheet.create({

 container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: 'center'
  }

})
reactjs react-native firebase-authentication expo react-native-firebase
1个回答
0
投票

当应用程序启动时,Firebase可能需要与其服务器进行通信,以检查用户身份验证是否仍然有效。这是异步发生的,并且在进行时,firebase.auth().currentUser将返回null。这就是为什么您的<Text>Hello {firebase.auth().currentUser.email} </Text>不起作用的原因:您正在.email上调用null

解决方案是检查用户是否已通过身份验证:

<Text>Hello {firebase.auth().currentUser ? firebase.auth().currentUser.email : "unknown user"} </Text>

您通常希望在常规的JavaScript代码中而不是在render()方法中执行此操作,因为这会使代码更难阅读。

实际上,您可能希望将user推入对象的状态,并在身份验证状态更改时刷新它。为此,您可以attach a so-called auth state listener并从其回调中调用setState

componentWillMount() {
  firebase.auth().addAuthStateChangedListener((user) => {
    this.setState({ user });
  });
}

然后在渲染方法中,您将要做:

<Text>Hello {user ? user.email : "unknown user"} </Text>
© www.soinside.com 2019 - 2024. All rights reserved.