React-native 处理登录和注册

React-native handle login and signup

用户点击登录按钮后,我想按以下顺序执行 3 个步骤 1)在服务器上注册用户 2)登录用户到服务器 3) 打开主页

this.props.login 和 this.props.signUp 是异步函数,来自 action。 让它们按特定顺序依次工作的正确方法是什么? 我应该使用回调还是一些生命周期方法?

请举例说明如何让它工作。

谢谢!

...
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() 中使用异步等待。这样 login() 只会在 signUp() 承诺解决后被调用。

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 中。这将与异步等待相同。 login() 将在 signUp() 解析后调用。如果您只想在用户登录后导航,则可以将 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')
          }
        ])
      )
  }