React-native - Firebase onAuthStateChanged 无法正常工作

React-native - Firebase onAuthStateChanged not working correctly

我无法在我的 react-native 应用程序中保持 firebase 会话。这个问题几乎与 但那里提供的答案对我没有用。

目前我登录如下图:

export const loginUser = ({ email, password }) => {
  return (dispatch) => {
    dispatch({ type: LOGIN_USER });

    firebase.auth().signInWithEmailAndPassword(email, password)
      .then(user => loginUserSuccess(dispatch, user))
      .catch(() => loginUserFailed(dispatch))

  };
};

我的会话已创建,我可以访问存储在 firebase 上的用户对象。

当我按下 Cmd+R 或关闭应用程序并重新打开时,我的会话就消失了。我的 app.js 文件的 componentWillMount() 部分中有 运行 以下内容:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    console.log('user is logged');
  } else {
    console.log('not logged in')
  }
});

每当我刷新应用程序或完全关闭它并重新打开时,我都会收到 'not logged in' 响应。

我也试过查询:

firebase.auth().currentUser

但在 returns null

的地方遇到同样的问题

我做错了什么?

是否有我缺少的保持会话活动的特定方法?

这个问题是因为您在登录后没有执行 Firebase.auth().signOut()。尝试注销(为了测试,您始终可以在 componentWillMount 函数中注销),您将能够看到 onAuthStateChanged 通知。

我 post 回答这个问题已经有一段时间了,但我想我会 post 我的解决方案。

事实证明,我的初始设置(有点)奏效了。我的意思是,onAuthStateChanged 需要一些时间才能收到来自 firebase 的回复,在此期间,应用程序的其余部分加载时认为用户未登录,因为这是默认状态。

我设法通过将 onAuthStateChanged 逻辑移出 app.js 并移至 componentWillMount 中的初始主页来解决这个问题。现在看起来像这样:

componentWillMount() {
const { navigate } = this.props.navigation;
firebase.auth().onAuthStateChanged((user) => {
  if (user) {

    SplashScreen.hide()
    this.setState({ loading: false })

    this.props.persistedUserLoginSuccess({user, navigate})

    this.props.fetchUserData();

  } else {

    SplashScreen.hide()
    this.setState({ loading: false })

  }
});

此外,我设法通过强制启动画面保持在正在查询身份验证的状态来改善用户体验。完成后,启动画面被隐藏,应用程序加载为登录应用程序或用户尚未登录的应用程序。