如何在React Native中实现回调函数?

Moh*_*din 6 javascript reactjs react-native

我只是想知道如何在onPress函数中实现回调函数。我想确保第一个功能完成然后触发第二个过程。

onPress={() => {
          onSignIn(); //run this function first
          if(_values.success == 1){ //then run this after onSignIn() function completed
            navigation.navigate("SignedIn");
          } 
        }}
Run Code Online (Sandbox Code Playgroud)

onSignIn()

export const onSignIn = async () => {
  if (_values.username && _values.password) { 
    fetch("http://localhost:3001/sessions/create", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: _values.username,
        password: _values.password
      })
    })
    .then((response) => response.json())
    .then((responseData) => {
      if(responseData.access_token){
         AsyncStorage.setItem(USER_KEY, responseData.access_token);
        _values.success = 1;
        alert("Login successfully!");
        return _values.success;
      } else {
        alert("Wrong username and password!");
        _values.success = 0;
        return _values.success;
      }
    })
    .done();
  } else{
    alert("Please enter your username and password.");
  }
}
Run Code Online (Sandbox Code Playgroud)

参考: https: //github.com/datomnurdin/auth-reactnative

Dam*_*ero 1

首先,onSign()必须是一个async函数,不要添加该done()函数,你想稍后处理它:

  export const onSignIn = async () => {
  if (_values.username && _values.password) { 
    fetch("http://localhost:3001/sessions/create", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: _values.username,
        password: _values.password
      })
    })
    .then((response) => response.json())
    .then((responseData) => {
      if(responseData.access_token){
         AsyncStorage.setItem(USER_KEY, responseData.access_token);
        _values.success = 1;
        alert("Login successfully!");
        return _values.success;
      } else {
        alert("Wrong username and password!");
        _values.success = 0;
        return _values.success;
      }
    })
  } else{
    throw "Please enter your username and password.";
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,你只需这样做:

onPress={() => {
          onSignIn().then( (values) => {
            if(values.success == 1){
               navigation.navigate("SignedIn");
            } 
          })
          .catch(error => console.log(error)) //do something in case onSignIn fails 
        }}
Run Code Online (Sandbox Code Playgroud)