当前,我正在尝试使用React和Firebase身份验证创建一个Web应用。
问题是我不知道如何在呈现组件之前让我的应用检查用户是否已登录。我确实知道应该通过onAuthStateChanged方法解决此问题,但是我不确定如何以及在何处使用它。以下是我的MainPage的结构。
主页
const MainPage= () => {
return (
<PageTemplate>
{...}
<PageTemplate>
);
}
PageTemplate
const PageTemplate= ({children}) => {
return (
<div>
<Header>
<div>
{children}
</div>
</div>
);
};
标题
class HeaderContainer extends Component {
render(
return (
if(logged in){
<LogOutButton />
}else{
<LoginButton />
}
);
)
}
起初,我尝试在PageTemplate的componentDidMount中调用onAuthStateChanged方法,但很快意识到,PageTemplate的componentDidMount是在Header之后调用的,这导致用户已经登录时仅呈现一秒钟。
然后我尝试在Header的componentDidMount中调用onAuthStateChanged方法,但是感觉不对,因为每次我需要检查用户是否登录时,都必须在PageTemplate的子组件中调用onAuthStatechanged方法。>
我很困惑在哪里使用onAuthStateChanged方法。
有人可以帮忙吗?我真的很感谢您的建议。