Firebase 在react本机异步函数内调用方法重定向,是否可能?

Firebase 在react本机异步函数内调用方法重定向,是否可能?,firebase,react-native,promise,firebase-authentication,Firebase,React Native,Promise,Firebase Authentication,我正在制作一个react本机应用程序,并使用firebase验证我的用户凭据,如下所示:(编辑以包含更多代码) import React,{Component}来自'React'; 从“react native”导入{文本、视图、按钮、文本输入、警报}; 从“../config/firebase”导入{firebaseRef}; 类寄存器扩展组件{ 建造师(道具){ 超级(道具); this.state={firstName:'',lastName:'',电子邮件:'',密码:'',confir

我正在制作一个react本机应用程序,并使用firebase验证我的用户凭据,如下所示:(编辑以包含更多代码)

import React,{Component}来自'React';
从“react native”导入{文本、视图、按钮、文本输入、警报};
从“../config/firebase”导入{firebaseRef};
类寄存器扩展组件{
建造师(道具){
超级(道具);
this.state={firstName:'',lastName:'',电子邮件:'',密码:'',confirmPassword:'',成功:true};
this.register=this.register.bind(this);//授予对状态对象的访问权
}
重定向(){
this.props.navigation.navigate('home');
}
寄存器(){
firebaseRef.auth().createUserWithEmailAndPassword(this.state.email,this.state.password)。然后(函数(用户){
Alert.Alert('恭喜','您已成功注册您的电子邮件地址');
}, 
函数(错误){
Alert.Alert('注册失败','失败');
console.log(错误代码);
console.log(错误消息);
这个。重定向();
});
}
注册失败(){
Alert.Alert('注册失败','失败');
this.setState({success:false});
}
成功注册(){
Alert.Alert('做得好','您已成功注册');
}
render(){
返回(
this.setState({firstName:input})}
值={this.props.input}
/>
this.setState({lastName:input})}
值={this.props.input}
/>
this.setState({email:input})}
值={this.props.input}
/>
this.setState({password:input})}
值={this.props.input}
/>
this.setState({confirmPassword:input})
值={this.props.input}
/>
{this.state.firstName}
{this.state.lastName}
{this.state.email}
{this.state.password}
{this.state.confirmPassword}
this.register()}>
)
}
}

导出默认寄存器; 如果调用这样的方法.redirect(),它将返回错误“this.redirect不是函数”


任何帮助都将不胜感激,提前感谢。

解决此问题的一种方法是:将其存储在另一个变量中,并使用该变量调用函数

register(){
  var that = this;
  firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then(function(user) {
  Alert.alert('Congratulations', 'You have successfully registered your email address');
}, 
  function(error) {
    Alert.alert('Registration Failed', 'failure');
    console.log(error.code);
    console.log(error.message);
    that.redirect();
  });
}
您还可以按以下方式绑定函数

<Button title={'REGISTER'} onPress={this.register.bind(this)}></Button>


能否请您包含更多的代码,包括调用此.redirect()的位置。很可能您没有绑定呼叫,但是如果不查看更多信息,就无法确定code@coderhacker更新的精彩解决方案!我使用了“var that=this”;但是为什么绑定我的onpress是个好主意呢?它做什么?只是一个提示:当你有一个回调时,总是用这个绑定。这确保函数中使用的“This”是指向组件的。(这是实现您在constructor中所做的另一种方法)。我见过很多人在回拨时这样做。
<Button title={'REGISTER'} onPress={this.register.bind(this)}></Button>