首页 > 解决方案 > Firebase,用户注册和导航问题

问题描述

我正在使用 React Native、Firebase 和 react-navigator。

在 LoadingScreen 组件中,我观察到状态变化(onAuthStateChanged)

    componentDidMount() {
        this.timer = setInterval(
            () => firebase.auth().onAuthStateChanged(user => {
                user ? this.props.navigation.navigate("App") : this.props.navigation.navigate("Auth");
            }),
            30,
        );
    }

在 ChooseRole 组件的 AuthStack 中,我有一个函数,我想在其中注册用户以及要执行的角色。

if (this.state.role === 'child') {
                Firebase
                    .auth ()
                    .createUserWithEmailAndPassword (email, password)
                    .then (() => {
                        const addChildRole = fc.httpsCallable (('addChildRole'));
                        addChildRole ({email: this.state.email}). then ((result) =>
                            this.setState ({role: result}));
                    })
                    .catch (errorMessage => {
                        console.log (errorMessage)
                    });
            })

问题是在 .then() 调用女巫之前,我添加了一个角色,身份验证状态可能会更改并导航到应用程序。在 AppStack 中,Direction 组件,基于角色,我想定位子组件或父组件,但是通过调用

firebase.auth (). CurrentUser.getIdTokenResult ()
         .then ((idTokenResult) => {
         if (idTokenResult.claims.parent || idTokenResult.claims.child) {
}

idTokenResult.claims.parent 和 idTokenResult.claims.child 给出未定义的。

我想处理给用户注册和登录的角色,然后使用 Direction.js 移动到适当的组件。

你知道如何解决这个问题吗?

标签: javascriptfirebasereact-nativefirebase-authenticationreact-navigation

解决方案


不一定是您的问题的原因,但时间太长而无法发表评论。

无需反复调用onAuthStateChanged。你可以只调用一次,它会从那一刻起监听身份验证状态的变化。当你这样做时,在很短的时间间隔内调用它一定会带来问题。

componentDidMount改为执行此操作:

componentDidMount() {
    firebase.auth().onAuthStateChanged(user => {
        user ? this.props.navigation.navigate("App") : this.props.navigation.navigate("Auth");
    });
}

问题的原因很可能onAuthStateChanged是在您的数据库写入完成之前触发。您可以通过添加一些日志语句轻松地验证这一点。

如果是,您有两个主要选项来解决此问题:

  1. 不要在 中使用onAuthStateChanged侦听器componentDidMount,而只需检查 的值firebase.auth().currentUser。这不使用侦听器,因此不会干扰数据库写入。
  2. 在创建用户之前删除onAuthStateChanged它,这样它就不会触发。您可以通过保留调用的返回值来做到这一点onAuthStateChanged,这是一个取消订阅函数。所以类似于:

    componentDidMount() {
        stopAuthStateListener = firebase.auth().onAuthStateChanged(user => {
            ...
    

    接着:

    if (this.state.role === 'child') {
        stopAuthStateListener();
        Firebase
            .auth ()
            .createUserWithEmailAndPassword (email, password)
            ...
    

推荐阅读