简体   繁体   English

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

[英]How to implement a callback function in React Native?

I'm just wondering how to implement callback function in onPress function.我只是想知道如何在onPress函数中实现回调函数。 I want to make sure the first function completed then the second process triggered.我想确保第一个功能完成然后第二个过程触发。

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

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

By "wait for onSignIn to complete" I guess you mean it is an asynchronous function, you can then use the await operator to wait for it to be over通过“等待onSignIn完成”,我猜您的意思是它是一个异步函数,然后您可以使用await运算符来等待它结束

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

Then you will ahve to add async to your onSignIn function :然后你将async添加到你的 onSignIn 函数中:

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

Here is a more 'React-y' way too handle your full process :这是一种更“反应式”的方式来处理您的整个过程:

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>
        )
    }
}

EDIT :编辑 :

Instead of returning a 0 or a 1, you could simply return a boolean in your function.您可以简单地在函数中返回一个布尔值,而不是返回 0 或 1。 Also, now that you are using the more modern async/await operators, you can remove the then functions :此外,现在您正在使用更现代的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.");
    }
}

Now, here is how you will fetch the response from this function :现在,您将如何从此函数获取响应:

export default class Example extends Component {

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

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

            </div>
        )
    }
}

Return a Promise from the method and add .then() to the function call从方法返回一个 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;
}

Call the method like this:像这样调用方法:

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

first, onSign() must be an async function, don't add the done() function,you want to handle it latter:首先,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.";
  }
}

then, you just do:然后,您只需执行以下操作:

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

This code should help you此代码应该可以帮助您

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM