k10*_*10a 1 firebase reactjs firebase-authentication
我在我的React项目中使用Firebase。用户尚未登录时,应用程序无法重定向到“登录”页面的问题。
在“我Home.js拥有”页面中,该页面仅允许已登录应用程序的用户使用。
class Home extends React.Component {
constructor(props) {
super(props);
}
logout = () => {
firebase.auth().signOut();
this.props.history.push("/login");
};
render() {
if (firebase.auth().currentUser === null) {
return <Redirect to="/login" />;
}
return (
<div>
<div>
<Button variant="contained" color="primary" onClick={this.logout}>
Google Logoout
</Button>
</div>
</div>
);
}
}
export default withRouter(Home);
Run Code Online (Sandbox Code Playgroud)
实际上,我用于通过分类用户是否登录firebase.auth().currentUser。
一个简单的。可以通过使用onAuthStateChangedfirebase 来实现,如下所示:
firebase.auth().onAuthStateChanged(user => {
if (user) {
history.push("/dashboard");
renderApp();
} else {
history.push("/login");
renderApp();
}
});
Run Code Online (Sandbox Code Playgroud)
如果有用户,请将该用户重定向到我的情况下的仪表板,如果没有,请将该用户重定向到登录。
| 归档时间: |
|
| 查看次数: |
31 次 |
| 最近记录: |