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

标签 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");
          } 
        }}

登录登录()

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.");
  }
}

引用:https://github.com/datomnurdin/auth-reactnative

最佳答案

从方法中返回一个 Promise 并将 .then() 添加到函数调用中

export const onSignIn = async () => {

  const promise =  new  Promise(async (resolve, reject) => {

    try {
    //do something and return result on success
    resolve(result);

   }catch(msg) { reject(msg);}

   });

  return promise;
}

像这样调用方法:

onSignIn ().then(
     (response,error) => {
     //get callback here
  });

关于javascript - 如何在 React Native 中实现回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53933642/

相关文章:

javascript - 在 Javascript ( js ) 文件中加载的 jQuery

javascript - 处理受引用影响的状态的 react 方式是什么

javascript - 如何创建跨所有平台的共享单例组件?

javascript - 在 React App 中使用 Axios 将响应数据下载为流

javascript - 使用 Map 函数编写 React 组件时,对象作为 React Child 无效

javascript - 如何测试 JavaScript 代码的性能?

javascript - 解释这个正则表达式 js

reactjs - 生成构建错误 : [vite:load-fallback] Could not load

reactjs - 由于 useState 而导致 React Native 中的无限循环

android - React Native 应用程序仅允许 Google Play 商店上的 410 台设备