1

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

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

4

1 回答 1

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 />;
  }
}
于 2018-01-12T09:13:37.887 回答