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

时间:2018-01-11 23:31:59

标签: react-native-firebase

我正在使用react-native-firebase,我想确保应用的用户stay logged in across restarts。目前我已经通过黑客攻击完成了它(一旦应用程序启动就会自动重新登录用户),但我想了解是否有更简单的方法。

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

1 个答案:

答案 0 :(得分:3)

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

查看此中篇文章,以便更好地解释发生了什么: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 />;
  }
}