首页 > 解决方案 > 在 React.JS 中刷新后如何让用户保持登录到 firebase

问题描述

这里有一个类似的问题,建议的答案似乎对我不起作用。

这是我使用 Firebase 移动登录来登录 ReactJS 的方式。我还在登录时设置身份验证状态持久性(请参见下面的代码)。

但是,当我在登录后刷新页面时,用户对象消失了,即“用户未登录”消息打印在 componentDidMount 中。

我可能做错了什么?

class SignInScreen extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isSignedIn: false, 
    };

  }

  // Configure FirebaseUI.
  uiConfig = {
    // Popup signin flow rather than redirect flow.
    signInFlow: "popup",

    signInOptions: [
      {
        provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID,
        defaultCountry: "US",
      },
    ],
    callbacks: {
      // Avoid redirects after sign-in.
      signInSuccessWithAuthResult: () => false,
    },
  };

  // Listen to the Firebase Auth state and set the local state.
  componentDidMount() {
    this.unregisterAuthObserver = firebase.auth().onAuthStateChanged((user) => {
      this.setState({ isSignedIn: !!user });
      if (user != null) {
        this.setAuthPersistence(); // Setting state persistence here
      }
    });

  if(firebase.auth().currentUser){
    console.log("User is already signed in")
  }else{
    console.log("User is not signed in")
  }
}


  setAuthPersistence = () => {
    firebase
      .auth()
      .setPersistence(firebase.auth.Auth.Persistence.LOCAL)
      .then(function() {
        console.log("Local persistence set");
      })
      .catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        console.log("Local persistence has not been set");
      });
  };

  // Make sure we un-register Firebase observers when the component unmounts.
  componentWillUnmount() {
    this.unregisterAuthObserver();
  }

  render() {
    //Displaying firebase auth when user is not signed in
    if (!this.state.isSignedIn) {
      return (
        <div>
          <StyledFirebaseAuth
            uiConfig={this.uiConfig}
            firebaseAuth={firebase.auth()}
          />
        </div>
      );
    }
    return <Redirect to="/signedInUser" />;
  }
}

export default SignInScreen;

标签: reactjsfirebasefirebase-authentication

解决方案


与您链接的答案相同,您if(firebase.auth().currentUser)在 Firebase 异步刷新身份验证状态之前运行,因此在用户再次登录之前。

任何需要响应身份验证状态的代码都需要在onAuthStateChanged回调中。所以:

  componentDidMount() {
    this.unregisterAuthObserver = firebase.auth().onAuthStateChanged((user) => {
      this.setState({ isSignedIn: !!user });
      if (user != null) {
        this.setAuthPersistence(); // Setting state persistence here
      }
      if(firebase.auth().currentUser){
        console.log("User is already signed in")
      }else{
        console.log("User is not signed in")
      }
    });
  }

推荐阅读