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

odi*_*ino 1 react-native-firebase

我正在使用react-native-firebase并且我想确保用户在应用程序重新启动保持登录状态。现在我已经通过 hack 完成了(一旦应用程序启动,用户就会自动重新登录),但我想了解是否有更简单的方法来做到这一点。

我看到该setPersistence方法已禁用,尽管我不清楚什么是最佳选择...

小智 6

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 />;
  }
}
Run Code Online (Sandbox Code Playgroud)