Javascript react js应用程序中的firebase未将身份验证对象设置为打开状态

Javascript react js应用程序中的firebase未将身份验证对象设置为打开状态,javascript,reactjs,firebase,firebase-authentication,Javascript,Reactjs,Firebase,Firebase Authentication,我正在使用firebase作为身份验证工具开发一个简单的react js应用程序。这是我的app.js ***some imports class App extends React.Component { constructor() { super(); this.state = { currentUser: null } } unsubscribeFromAuth = null; component

我正在使用firebase作为身份验证工具开发一个简单的react js应用程序。这是我的app.js

***some imports

class App extends React.Component {
    constructor() {
        super();
        this.state = {
            currentUser: null
        }
    }

unsubscribeFromAuth = null;

componentDidMount() {
    this.unsubscribeFromAuth = auth.onAuthStateChanged(async  userAuth => {
        if(userAuth){
            const userRef = await createUserProfileDocument(userAuth);
            userRef.onSnapshot(snapShot => {
                this.setState({
                    currentUser: {
                        id: snapShot.id,
                        ...snapShot.data()
                    }
                },() => {console.log(this.state)});
            });

        }
        else
        {
            this.setState({ currentUser: userAuth });
            
        }

    });

}

componentWillUnmount() {
    this.unsubscribeFromAuth();
}



render() {
    return (
        <div>
            <h1>{this.state.currentUser.email}</h1>
        </div>
    )
}
}





export default App
***某些导入
类应用程序扩展了React.Component{
构造函数(){
超级();
此.state={
当前用户:空
}
}
unsubscribeFromAuth=null;
componentDidMount(){
this.unsubscribeFromAuth=auth.onAuthStateChanged(异步userAuth=>{
if(userAuth){
const userRef=await createUserProfileDocument(userAuth);
userRef.onSnapshot(快照=>{
这是我的国家({
当前用户:{
id:snapShot.id,
…snapShot.data()
}
},()=>{console.log(this.state)});
});
}
其他的
{
this.setState({currentUser:userAuth});
}
});
}
组件将卸载(){
这是。unsubscribeFromAuth();
}
render(){
返回(
{this.state.currentUser.email}
)
}
}
导出默认应用程序
问题是,当我运行项目时,它会给出此错误
currentUser为null
,如果我删除app.jsx中的
{this.state.currentUser.email}
,控制台会在5或6秒延迟后记录状态,并且该日志包含我想要的内容,即currentUser

因此,当我使用
{this.state.currentUser.email}

TypeError:this.state.currentUser为空

这就是当我删除
(等待5或6秒后)时在控制台中得到的

当您试图访问电子邮件时,它还不存在。当您的组件初始化时,在componentDidMount之前调用render。你试图访问的电子邮件仍然需要设置为你的状态,因此你得到的错误

您应该在渲染类中使用条件语句

render(){
返回(
{this.state.currentUser&({this.state.currentUser.email}}
)
}
这样你的应用程序就不会崩溃,你甚至可以在从firebase获取状态数据时向用户显示一些默认UI