首页 > 解决方案 > React native firebase - facebook登录未触发onAuthStateChanged监听器

问题描述

这是我在使用 RNFB facebook 登录时遇到的第二个问题。

我遵循RNFB 提供的官方代码示例....代码如下

问题出在这行firebase().signInWithCredential(facebookCredential);....它没有触发 firebase 侦听auth().onAuthStateChanged 器所有其他代码都按应有的方式运行,并且facebookCredential变量已正确填充

import { firebase } from '@react-native-firebase/auth';

  onFacebookButtonPress = async () => {
    // Attempt login with permissions
    const result = await LoginManager.logInWithPermissions([
      'public_profile',
      'email',
    ]);

    if (result.isCancelled) {
      throw 'User cancelled the login process';
    }

    // Once signed in, get the users AccesToken
    const data = await AccessToken.getCurrentAccessToken();

    if (!data) {
      throw 'Something went wrong obtaining access token';
    }

    // Create a Firebase credential with the AccessToken
    //const facebookCredential = firebase.FacebookAuthProvider.credential(data.accessToken);
    const facebookCredential = firebase.auth.FacebookAuthProvider.credential(
      data.accessToken,
    );

    // Sign-in the user with the credential
    firebase().signInWithCredential(facebookCredential);
  };

标签: react-nativefirebase-authenticationreact-native-firebase

解决方案


您不应该等到出现问题后再添加 try/catch。signInWithCredential返回您处理的许多不同类型的错误。从文档:

firebase.auth().signInWithCredential(credential).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // The email of the user's account used.
  var email = error.email;
  // The firebase.auth.AuthCredential type that was used.
  var credential = error.credential;
  if (errorCode === 'auth/account-exists-with-different-credential') {
    alert('Email already associated with another account.');
    // Handle account linking here, if using.
  } else {
    console.error(error);
  }
 });

请也处理其他错误情况:

auth/account-exists-with-different-credential

身份验证/无效凭据

身份验证/不允许操作

身份验证/用户禁用

和更多。


推荐阅读