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

时间:2018-04-17 08:26:21

标签: javascript firebase react-native firebase-authentication react-navigation

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

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);
}

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

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

我的退出按钮如下所示:

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

1 个答案:

答案 0 :(得分:6)

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

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