如何在 React Native Firebase 上启用持久性?

How to enable persistence on React Native Firebase?

我正在使用该应用程序的 react-native-firebase and I want to make sure that the user stay logged in across restarts。现在我已经通过 hack 完成了它(应用程序启动后自动重新登录用户)但我想了解是否有更简单的方法来做到这一点。

我看到 setPersistence 方法是 disabled,但我不清楚什么是最好的选择...

setPersistence 控制数据库持久性,而不是身份验证持久性。默认情况下启用身份验证持久性,因此默认情况下您的用户将在重新启动后保持登录状态。但是,当 Firebase 正在检查持久身份验证令牌的有效性时,应用程序重新启动时会有一小段延迟。

查看这篇 Medium 文章以更好地解释正在发生的事情:https://blog.invertase.io/getting-started-with-firebase-authentication-on-react-native-a1ed3d2d6d91

请特别注意 Checking the current authentication state 部分,其中解释了如何使用 onAuthStateChanged

为了完整起见,我在此处包含了完整示例。

import React from 'react';
import firebase from 'react-native-firebase';
// Components to display when the user is LoggedIn and LoggedOut 
// Screens for logged in/out - outside the scope of this tutorial
import LoggedIn from './LoggedIn';
import LoggedOut from './LoggedOut';
export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      loading: true,
    };
  }
  /**
   * When the App component mounts, we listen for any authentication
   * state changes in Firebase.
   * Once subscribed, the 'user' parameter will either be null 
   * (logged out) or an Object (logged in)
   */
  componentDidMount() {
    this.authSubscription = firebase.auth().onAuthStateChanged((user) => {
      this.setState({
        loading: false,
        user,
      });
    });
  }
  /**
   * Don't forget to stop listening for authentication state changes
   * when the component unmounts.
   */
  componentWillUnmount() {
    this.authSubscription();
  }
  render() {
    // The application is initialising
    if (this.state.loading) return null;
    // The user is an Object, so they're logged in
    if (this.state.user) return <LoggedIn />;
    // The user is null, so they're logged out
    return <LoggedOut />;
  }
}