【问题标题】:How to wait for persisted user from firebase auth in React Native如何在 React Native 中等待来自 firebase 身份验证的持久用户
【发布时间】:2019-09-29 22:22:42
【问题描述】:

我在我的 React Native 应用程序(通过 expo)中使用 firebase 身份验证,身份验证通过观察者工作正常,包括持久用户:

import firebase from "firebase";

firebase.auth().onAuthStateChanged(user => {
    if (user) {
        this.props.setUser(user);
    }
}).bind(this);

我会显示一个带有登录/注册的登录屏幕,如果用户使用帐户登录,我会转发到主应用程序。应用程序启动后,在加载持久用户时,onAuthStateChanged 方法需要一段时间才能触发,这导致我的应用程序在短时间内显示此登录屏幕,然后导航离开。 在正确确定身份验证状态之前,我希望有一个加载屏幕。

但是如果没有持久用户,onAuthStateChanged 永远不会触发,所以我没有要等待的特定事件。我可以使用超时计时器,但这似乎是一个糟糕的解决方案,因为必要的等待时间可能会因硬件和连接速度而有很大差异。

如何正确解决这个问题,即我如何知道没有持久用户?

【问题讨论】:

    标签: javascript firebase react-native firebase-authentication expo


    【解决方案1】:

    Firebase error block when user does not persist

    var isLoading = true;
    
       firebase.auth().onAuthStateChanged(user => {
            if (user) {
                isLoading = false;
                this.props.setUser(user);
            }
        }, error => {
           isLoading = false;
       }
    }).bind(this);
    

    【讨论】:

      【解决方案2】:

      onAuthStateChanged 只有在完成加载后才会触发它的功能。因此,当触发时,您可以假设身份验证已完成加载,而不管用户的值如何。我最终使用 expo-splash-screen 在加载身份验证时显示加载屏幕。

      例子:

      export default () => {
          const [isAuthenticationLoaded, setIsAuthenticationLoaded] = React.useState(false);
      
          firebase.auth().onAuthStateChanged((user) => {
              if (user) setUser(user);
              setIsAuthenticationLoaded(true);
          });
      
         React.useEffect(() => {
              SplashScreen.preventAutoHideAsync();
          }, []);
      
          React.useEffect(() => {
              if (isAuthenticationLoaded) {
                  SplashScreen.hideAsync();
              }
          }, [isAuthenticationLoaded]);
          ...
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-18
        • 1970-01-01
        • 2019-06-25
        • 1970-01-01
        • 2018-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-10
        相关资源
        最近更新 更多