我在我的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);
实际上,我用于对用户是否通过firebase.auth().currentUser
登录进行分类。
答案 0 :(得分:5)
一个简单的。可以通过使用Firebase中的onAuthStateChanged
来完成此操作,
firebase.auth().onAuthStateChanged(user => {
if (user) {
history.push("/dashboard");
renderApp();
} else {
history.push("/login");
renderApp();
}
});
如果有用户,请将该用户重定向到我的情况下的仪表板,如果没有,请将该用户重定向到登录。