用户未登录应用程序时如何重定向到登录页面

时间:2019-11-24 00:15:04

标签: reactjs firebase 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);

实际上,我用于对用户是否通过firebase.auth().currentUser登录进行分类。

1 个答案:

答案 0 :(得分:5)

一个简单的。可以通过使用Firebase中的onAuthStateChanged来完成此操作,

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

如果有用户,请将该用户重定向到我的情况下的仪表板,如果没有,请将该用户重定向到登录。