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

时间:2018-12-26 14:55:09

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

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

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

4 个答案:

答案 0 :(得分:1)

从方法中返回一个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
  });

答案 1 :(得分:0)

首先,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.";
  }
}

然后,您只需:

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

答案 2 :(得分:0)

此代码应为您提供帮助

async onPressFunc() {
  await onSignIn(); //run this function first

  if(_values.success == 1){ //then run this after onSignIn() function completed
    navigation.navigate("SignedIn");
  } 
}

onPress={this.onPressFunc}

答案 3 :(得分:0)

通过“等待onSignIn完成”,我想你是说它是一个异步函数,然后可以使用await运算符等待它结束

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

然后,您将async添加到onSignIn函数中:

onSignIn = async () => {console.log("signing in")}

这也是处理您整个过程的一种“反应式”方法:

import React, { Component } from 'react'

export default class Example extends Component {

    onSignIn = async () => {
        console.log('singing in....')
    }

    pressEvent = async event => {
        await this.onSignIn(); //run this function first
        if (_values.success == 1) { //then run this after onSignIn() function completed
            navigation.navigate("SignedIn");
        }
    }

    render() {
        return (
            <div onPress={this.pressEvent}>

            </div>
        )
    }
}

编辑:

代替返回0或1,您可以简单地在函数中返回布尔值。另外,既然您正在使用更现代的async/await运算符,则可以删除then函数:

export const onSignIn = async () => {
    if (_values.username && _values.password) {
        const response = await 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
            })
        })
        const responseData = JSON.parse(response)
        if (responseData.access_token) {
            AsyncStorage.setItem(USER_KEY, responseData.access_token);
            alert("Login successfully!");
            return true
        } else {
            alert("Wrong username and password!");
            return false
        }
    } else {
        alert("Please enter your username and password.");
    }
}

现在,这是从此函数获取响应的方法:

export default class Example extends Component {

    pressEvent = async event => {
        if (await onSignIn()) navigation.navigate("SignedIn");
    }

    render() {
        return (
            <div onPress={this.pressEvent}>

            </div>
        )
    }
}