还有一个类似的问题,here,建议的答案似乎对我不起作用。
这就是我如何使用firebase移动登录来登录ReactJS。我还设置了登录时的身份验证状态持久性(参见下面的代码)。
但是,当我在登录后刷新页面时,用户对象消失了,即"User is not sign in“消息在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;发布于 2020-09-23 22:28:25
与您链接的答案相同,您的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")
      }
    });
  }https://stackoverflow.com/questions/64024613
复制相似问题