React Native - Firebase auth持久性不起作用

Nou*_*hir 9 persistence firebase react-native firebase-authentication

Firebase身份验证不会持续登录用户,每次刷新或重新打开应用程序时我都必须重新登录.

我已经尝试将持久性设置为本地,并且回调确实验证了它的设置,但持久性仍然无效

为了设置持久性我正在使用...

  //set auth persistence
  firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
    .then(function() {
      console.log("successfully set the persistence");

    })
    .catch(function(error){
    console.log("failed to ser persistence: " + error.message)
  });
Run Code Online (Sandbox Code Playgroud)

...登录时我正在使用此代码

firebase.auth().signInWithEmailAndPassword(email, password)
      .then((user) =>{
        this.checkAccountStatus(user.uid, user.email);
      })
      .catch(function(error) {
      // Handle Errors here.

      var errorCode = error.code;
      var errorMessage = error.message;

      console.log(errorMessage)
      // ...
    });
Run Code Online (Sandbox Code Playgroud)

这是我用来检查登录状态的代码......

if (firebase.auth().currentUser) {
        const currentUser = firebase.auth().currentUser;
        console.log("Signed in username" + currentUser.displayName);

        this.props.navigation.navigate('AppTab');
      }else{
        console.log("no user signed in");
        this.props.navigation.navigate('AuthTab');
      }
Run Code Online (Sandbox Code Playgroud)

如果有什么我做得不对

sou*_*tot 17

您不需要设置持久性.Firebase默认为您处理.您只需要调用此函数来检查用户是否已记录:

firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log('user is logged');
      }
}
Run Code Online (Sandbox Code Playgroud)

仅当用户已注销或清除应用数据时,才会触发此操作.

您可以在官方文档中找到更多详细信息:https://firebase.google.com/docs/auth/web/manage-users

希望能帮助到你.

  • 我改用这种方法... firebase.auth()。currentUser; ...使用Cmd + R刷新应用程序或从模拟器本身重新启动后,该方法将不起作用 (2认同)
  • @soutot 的答案是一个更好的方法。这里的官方文档说: 注意:currentUser 也可能为 null,因为 auth 对象尚未完成初始化。如果您使用观察者来跟踪用户的登录状态,则不需要处理这种情况。https://firebase.google.com/docs/auth/web/manage-users (2认同)