首页 > 解决方案 > 当用户未登录应用程序时如何重定向到登录页面

问题描述

我在我的 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

标签: reactjsfirebasefirebase-authentication

解决方案


一个简单的。这可以通过使用onAuthStateChangedfrom firebase 来完成,如下所示:

firebase.auth().onAuthStateChanged(user => {
   user ? history.push("/dashboard") : history.push("/login");
   renderApp();
});

如果有用户,将他重定向到我的案例仪表板,如果没有,将他重定向到登录。


推荐阅读