如何在React.JS中刷新后让用户登录firebase?

时间:2018-02-18 19:46:03

标签: reactjs firebase authentication firebase-authentication

安装组件时,我想呈现登录屏幕或应用程序,具体取决于用户登录的情况。但是,每次刷新时,用户都会被注销。我如何让他们登录?

应用程序组件:

 firebase.initializeApp(config); //init the firebase app...

class App extends Component {//this component renders when the page loads
constructor(props){
  super(props);

  this.state = {user: firebase.auth().currentUser};//current user
}
render(){
    if (this.state.user) {//if you are logged in
          return (
            <Application/>
          );
    } else {//if you are not logged in
          return (
            <Authentication/>
          );
    }
}

}

这是我用来登录用户的方法(工作正常):

let email = "some";
let password = "thing";
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, password);

3 个答案:

答案 0 :(得分:9)

用户的令牌会自动持久保存到本地存储,并在加载页面时读取。这意味着当您重新加载页面时,用户应该再次自动进行身份验证。

最可能的问题是您的代码未检测到此身份验证,因为您的App构造函数在Firebase重新加载并验证用户凭据之前运行。要解决此问题,您需要listen for the (asynchronous) onAuthStateChanged() event,而不是同步获取值。

constructor(props){
  super(props);
  firebase.auth().onAuthStateChanged(function(user) {
    this.setState({ user: user });
  });
}

答案 1 :(得分:1)

我在React中使用Firebase遇到了同样的问题。尽管Firebase具有内部持久性机制,但在重新加载浏览器页面时,您仍可能会遇到闪烁/故障,因为在您接收经过身份验证的用户的onAuthStateChanged侦听器会花费几秒钟。这就是为什么我使用本地存储在onAuthStateChanged侦听器中设置/重置它的原因。类似于以下内容:

firebase.auth.onAuthStateChanged(authUser => {
  authUser
    ? localStorage.setItem('authUser', JSON.stringify(authUser))
    : localStorage.removeItem('authUser')
});

然后可以在应用程序启动时在React组件的构造函数中对其进行检索:

constructor(props) {
  super(props);

  this.state = {
    authUser: JSON.parse(localStorage.getItem('authUser')),
  };
}

您可以在here上详细了解它。

答案 2 :(得分:1)

我个人认为这种方式是最好,最简单的。

  state = {authUser: null,show:'none'};
 
     componentDidMount() {
    firebase.auth().onAuthStateChanged(user => {
       if (user) { this.setState({ authUser: true,show:'block'})} 
       else { this.setState({ authUser: false,show:'none'})}
    })
  }
  return{ /*important*/ this.state.authuser==false?
     <Login/>
     :this.state.authuser==true?
        <Home style={{display:this.state.show}}/>
        :<div>/*show loading/spash page*/
        </div>
   }

您还可以使用Home作为默认路由来添加路由(使用'/'不要使用确切的路径,而是使用),然后如果用户将其自动重新路由到登录名或注册名尚未登录。