为什么我的firebase onAuthStateChanged()会多次触发? (React Native)

时间:2022-01-24 08:51:05

My firebase method onAuthStateChanged() trigger several times when I sign in and out using firebase-authentication according to console.log. Isn't it supposed to trigger only once at login and once at logout. The result is that when signing out, the navigation to a previous page is triggered several times. Here's the code:

根据console.log使用firebase-authentication登录和注销时,我的firebase方法onAuthStateChanged()会多次触发。是不应该只在登录时触发一次,在登出时触发一次。结果是,当注销时,会多次触发到上一页的导航。这是代码:

componentDidMount() {
    fbAuth.onAuthStateChanged(user => this.loginFunc(user));
}

loginFunc(user) {
   if (user) {
     console.log('LOGGED IN');
}else {
  console.log('LOGGED OUT');
  this.props.navigation.navigate('FbLogin');
}
console.log('onAUTH LOGGED IN: ', user);
}

This is what the console looks like. As you can see both login and logout are triggered on just a single logout click. On login, it triggers twice....

这就是控制台的样子。正如您所看到的,只需单击一次注销即可触发登录和注销。登录时,它会触发两次....

LOGGED OUT
FbLogin.js:46 onAUTH:  null
LoggedIn.js:27 LOGGED OUT
LoggedIn.js:30 onAUTH LOGGED IN:  null
FbLogin.js:44 LOGGED OUT
FbLogin.js:46 onAUTH:  null

My logout button looks like this:

我的注销按钮如下所示:

<TouchableHighlight //LOGOUT
   style={{
      ...
   }}
   onPress={() => {
      fbAuth.signOut();
      this.setState({ loginState: "You are logged out" });
   }}
   >
      <Text>Logout</Text>
   </TouchableHighlight>

1 个解决方案

#1


1  

Yes this is normal, onAuthStateChanged will keep triggering, I solved this by using this code:

是的,这是正常的,onAuthStateChanged将继续触发,我通过使用此代码解决了这个问题:

  var authFlag = true;
  Firebase.onAuthStateChanged( user => {
    if(authFlag) {
      authFlag = false;
      if (user) {
        // Do something,
      }
      else {
        // Alert.alert("Auth Error")
      }
    }
  });

#1


1  

Yes this is normal, onAuthStateChanged will keep triggering, I solved this by using this code:

是的,这是正常的,onAuthStateChanged将继续触发,我通过使用此代码解决了这个问题:

  var authFlag = true;
  Firebase.onAuthStateChanged( user => {
    if(authFlag) {
      authFlag = false;
      if (user) {
        // Do something,
      }
      else {
        // Alert.alert("Auth Error")
      }
    }
  });