如何在React Native中成功运行firebase服务函数后运行回调函数

问题描述 投票:0回答:1

我有一个名为FirebaseSvc的firebase服务类,我在名为Register的组件中使用它。我想要做的是运行reducer函数作为firebase createUserWithEmailAndPassword函数的回调。

FirebaseSvc.js用户创建功能:

createAccount = async (user, success_callback, failed_callback) => {
    await firebase.auth()
        .createUserWithEmailAndPassword(user.email, user.password);
        .then(success_callback, failed_callback);
}

Register.js提交用户注册表:

handleSubmit = () => {
    const value = this._form.getValue();

    axios.post(Api.API_URL + 'user', {
        'user': this._form.getValue()
    })
    .then((response) => {
        const user_credentials = { email: response.data.user.email, password: value.password };

        if (response.status === 200) {
            firebaseSvc.fetchingSignInMethodsForEmail(
                user_credentials, 
                function(){
                    console.log('register success');
                    this.props.navigation.state.params.addUser(response.data.user);
                    this.props.navigation.state.params.addCoupledUsers(response.data.extra_data.coupled_users);
                    console.log('trying to navigate to homescreen');
                    this.props.navigation.navigate('HomeScreen');
                },
                function(){
                    console.log('register failed');
                }
            );

        }
    })
    .catch((error) => {
        console.log(error.config);
    });
}

用户成功注册后,我在控制台日志register success中收到此消息,然后它给出了一个错误说:

可能未处理的承诺拒绝(id:0)

TypeError:undefined不是对象(评估'this.props.navigation`)

reactjs firebase react-native
1个回答
1
投票

我看到了一些可以解决错误的方法:

  1. 使用箭头函数进行回调,将this正确绑定到组件实例。

替换此功能:

function() {
    console.log('register success');
    this.props.navigation.state.params.addUser(response.data.user); this.props.navigation.state.params.addCoupledUsers(response.data.extra_data.coupled_users);
    console.log('trying to navigate to homescreen');
    this.props.navigation.navigate('HomeScreen');
}

() => {
    console.log('register success');
    this.props.navigation.state.params.addUser(response.data.user);
    this.props.navigation.state.params.addCoupledUsers(response.data.extra_data.coupled_users);
    console.log('trying to navigate to homescreen');
    this.props.navigation.navigate('HomeScreen');
}
  1. firebaseSvc.fetchingSignInMethodsForEmail中的错误目前没有达到.catch方法,因此你看到Possible Unhandled Promise Rejection (id: 0)

要解决此问题,请在return之前添加firebaseSvc.fetchingSignInMethodsForEmail

return firebaseSvc.fetchingSignInMethodsForEmail(
                user_credentials, 
...
© www.soinside.com 2019 - 2024. All rights reserved.