Javascript Firebase、用户注册和导航问题

Javascript Firebase、用户注册和导航问题,javascript,firebase,react-native,firebase-authentication,react-navigation,Javascript,Firebase,React Native,Firebase Authentication,React Navigation,我正在使用React Native、Firebase和React navigator 在LoadingScreen组件中,我观察到状态更改(onAuthStateChanged) 在ChooseRole组件的AuthStack中,我有一个函数,我想在其中注册一个用户以及要执行的角色 if (this.state.role === 'child') {                 Firebase                     .auth ()                    

我正在使用React Native、Firebase和React navigator

在LoadingScreen组件中,我观察到状态更改(onAuthStateChanged)

在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中,方向组件基于角色,我希望以子组件或父组件为目标,但通过调用

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

idTokenResult.claims.parent和idTokenResult.claims.child提供未定义的

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

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

不一定是问题的原因,但太长了,无法发表评论

无需重复调用authStateChanged。您可以只调用它一次,从那一刻起,它将侦听身份验证状态的更改。在短时间内调用它肯定会带来问题

componentDidMount
中执行此操作:

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

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

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

  • 不要在
    componentDidMount
    中使用
    onAuthStateChanged
    侦听器,只需检查
    firebase.auth().currentUser
    的值即可。这不使用侦听器,因此不会干扰数据库写入
  • 在创建用户之前删除onAuthStateChanged,这样它就不会触发。您可以通过保持对
    onAuthStateChanged
    调用的返回值来实现这一点,这是一个unsubscribe函数。因此,大致如下:

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

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