首页 > 解决方案 > 与 react-redux-firebase 反应 isLoaded 是真的, isEmpty 似乎是假的,但 firebase.auth().currentUser 是 null - 可能是什么原因?

问题描述

所以我可能很难解释我遇到的这个问题,我无法始终如一地重现。我有一个我正在使用的 React 应用程序,react-redux-firebase并且我认为我已成功实施以跟踪用户会话。

我的 App.js 文件具有以下位或路由代码作为示例(使用react-router-dom):

<Route
    path="/signin"
    render={() => {
        if (!isLoaded(this.props.auth)) {
            return null;
        } else if (!isEmpty(this.props.auth)) {
            return <Redirect to="/posts" />;
        }
        return <Signin />;
    }}
/>

这可以正常工作。Signin当用户未登录或用户登录时,我会转到组件Posts。在Signin组件中,我有一些发生的逻辑:

        // sign the user in
        this.props.firebase.login({
            email: user.email,
            password: user.password
        }).then(response => {

            // detect the user's geolocation on login and save
            if (isLoaded(this.props.auth)) {
                const navigator = new Navigator();
                navigator.setGeoLocation(this.props.firebase);
            }

            // redirect user to home or somewhere
            this.props.history.push('posts');
            
        })

我正在像这样导入 isLoaded:

import { firebaseConnect, isLoaded } from 'react-redux-firebase';

条件工作正常,用户登录,然后isLoaded条件发生 - 这就是问题出现的地方。使用 isLoaded true 我会假设用户和所有 redux-firestore 用户属性都可以使用......但有时情况并非如此。在 navigator.setGeoLocation 通话中,我有这个:

setGeoLocation(propsFirebase, cb) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
            propsFirebase.auth().currentUser
                .getIdToken(/* forceRefresh */ true)
                .then((idToken) => {
                    ...
                });
            }
        )
    }
}

此时,propsFirebase.auth().currentUser 有时为 null(这源于传入的参数navigator.setGeoLocation(this.props.firebase);)。如果我再次尝试登录,那么它可以工作。我找不到任何一致的复制方式。

我在其他组件中也注意到了这一点。我不确定这是否是我的计算机进入睡眠状态时发生的问题,我应该重新启动整个 React 进程还是什么?有没有人见过类似的问题?如果是这样,在路由中检查用户状态时我可能会丢失什么?

如果需要更多代码,请告诉我...

标签: reactjsfirebasefirebase-authenticationreact-router-domreact-redux-firebase

解决方案


如果用户未登录, currentUser将为 null。当页面首次加载时,在加载用户令牌且用户对象可用之前,它也将为 null。如果您想在页面加载后异步加载后立即采取行动,您应该使用身份验证状态观察器来获取用户对象。

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    var uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

您可能还想阅读更多详细信息:为什么我的 currentUser == null 在 Firebase Auth 中?


推荐阅读