【问题标题】:Firebase and React Native: onAuthStateChanged doesn't get triggeredFirebase 和 React Native:onAuthStateChanged 不会被触发
【发布时间】:2020-07-25 11:39:51
【问题描述】:

所以我正在使用 Firebase 开发我的第一个 React 本机应用程序,我的代码中有以下结构:

ComponentDidMount(){
    this.verifySession();
    console.log("Component did mount");
}

verifySession = () =>{
    console.log("inside VS");
    firebase.auth().onAuthStateChanged(user =>{
        if(user){
            this.props.navigation.navigate('Dashboard');
            console.log("dashboard");
        }else{
            this.props.navigation.navigate('Login');
            console.log("Login");
        }
    });
}

问题是,我的 verifySession 函数没有被触发。实际上,我没有收到任何日志,所以我认为 ComponentDidMount 也没有被执行。此代码位于我的 LoadingScreen 组件中。

这是我初始化 Firebase conf 的 app.js:

import * as firebase from 'firebase';
import {firebaseConfig} from './data/config';


const Stack = createStackNavigator();
firebase.initializeApp(firebaseConfig);

我还为我的 LoadingScreen 尝试了以下方法:

import Dashboard from './dashboard';
import Login from './login';

render(){
    firebase.auth().onAuthStateChanged(function(user){
        if(user){
            return (<Dashboard/>);
        }else{
            return (<Login/>);
        }  
    });

    return(
        <View>
            <Text>Verifying session...</Text>
        </View>
    )
}

登录应该被渲染,但它显示“验证会话”,这让我想如果语句根本没有被执行。

对此事的任何想法/建议将不胜感激。

【问题讨论】:

  • 您尝试过记录 Firebase 吗?查看您的应用是否已真正连接。

标签: firebase react-native firebase-authentication react-navigation


【解决方案1】:

onAuthStateChanged 是为了添加一个观察者而不是直接调用。可能是它没有触发,因为用户的登录状态根本没有改变,而且您没有尝试让任何人登录,所以没有什么可以触发它。 尝试实现auth().createUserWithEmailAndPassword(email, password) 或 `auth().signInWithEmailAndPassword(email, password)' 并测试用户创建/登录。

这篇文章也可能有用;它将身份验证观察者放在一个单独的组件中,并允许您根据用户的登录状态在两个导航堆栈之间导航: https://heartbeat.fritz.ai/how-to-manage-authentication-flows-in-react-native-with-react-navigation-v5-and-firebase-860f57ae20d3

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 2022-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 2019-10-24
    • 2014-12-31
    相关资源
    最近更新 更多