用户点击登录按钮后,我想按照以下顺序执行3个步骤:1)在服务器上注册用户2)将用户登录到服务器3)打开主页
this.props.login和this.props.signUp是异步函数,来自动作。使它们按特定顺序一个接一个地工作的正确方法是什么?我应该使用回调还是一些生命周期方法?
请举例说明如何使其工作。
谢谢!
...
import { login, signUp} from 'action';
class Auth extends Component {
handleLogin(){
const { name, email, password} = this.props;
this.props.signUp( name, email, password)
this.props.login(email, password)
this.props.navigtion.navigate('Home')
}
render(){
return(
<View>
<Button
title='Login'
onPress={()=> this.handleLogin()}
/>
</View>
)
}
}
您可以在handleLogin()中使用async await。这样只有在signUp()promise解析后才会调用login()。
async handleLogin(){
const { name, email, password} = this.props;
await this.props.signUp(name, email, password)
await this.props.login(email, password)
this.props.navigtion.navigate('Home')
}
另一种方法是将login()放在signUp()的.then
中。这将与async await相同。 signUp()结算后将调用login()。如果您只想在用户登录后进行导航,则可以将navigate()放在login()的.then
中。
handleLogin(){
const { name, email, password} = this.props;
this.props.signUp(name, email, password)
.then(this.props.login(email, password)
.then(this.props.navigtion.navigate('Home'))
)
}
希望这可以帮助。
这就是我这样做的方式而且一切正常,但我不确定它在最佳实践和清晰的语法方面是否合适。
当用户单击按钮时,它会在检查所有输入之后运行_handleSignup(),它会逐步运行异步功能。
async _handleSignup() {
const { name, email, password, passwordConfirm, phone } = this.props;
if (name.length === 0 && email.length === 0) {
Alert.alert('Make sure all inputs is filled');
return;
} else if (password !== passwordConfirm) {
Alert.alert('Password not match');
return;
}
await this.props.signUp(name, email, password)
await this.props.login(email, password).then(
Alert.alert('Account created', [
{
text:'Login',
onPress: ()=> this.props.navigation.navigate('Category')
}
])
)
}