【问题标题】:How to return response to another functional component如何向另一个功能组件返回响应
【发布时间】:2021-08-04 13:55:39
【问题描述】:

我面临一个问题,即我创建了一个用于 api 调用的功能组件,我将参数和 api 名称作为函数参数。在这个方法中,我用 fetch 调用 api 并且我也得到了响应,但是当我返回响应时,它显示我未定义。其中有什么问题?

let formData = new FormData();
formData.append("apikey", Constant.API_KEY);
formData.append("email", email);

ApiCall.ApiCalling(formData, Constant.forget_password)
  .then((data) => {
      console.log('Response -> ', data); // Here getting undefined
  })


// New component ApiCall.js
export default {
async ApiCalling(params, apiName) {

    await NetInfo.fetch().then(async state => {
        if (state.isConnected == true) {

            console.log(Constant.BASE_URL + apiName);
            console.log(params);

            await fetch(Constant.BASE_URL + apiName, {
                method: 'POST',
                body: params
            })
                .then(results => results.json())
                .then((response) => {
                    console.log("Response - ", response); // Here getting  
                                                             proper response
                    return response;
                })
                .catch(function (error) {
                    console.log('There has been a problem with your fetch 
                    operation: ' + error.message);
                    throw error;
                });

        } else {
            alert("Please connect with internet")
        }
    });
}

}

【问题讨论】:

  • 尝试删除第一个承诺解析器。你可以得到(响应)-> console.log(response: ${JSON.stringify(response)})。希望它可以帮助您。
  • 同样的问题也会出现。

标签: react-native api react-hooks fetch react-functional-component


【解决方案1】:
// New component ApiCall.js
export default {
async ApiCalling(params, apiName) {
var result;  // Create one variable
await NetInfo.fetch().then(async state => {
    if (state.isConnected == true) {

        console.log(Constant.BASE_URL + apiName);
        console.log(params);

        await fetch(Constant.BASE_URL + apiName, {
            method: 'POST',
            body: params
        })
            .then(results => results.json())
            .then((response) => {
                console.log("Response - ", response);
                result = response;  // Assign response to that variable
            })
            .catch(function (error) {
                console.log('There has been a problem with your fetch 
                operation: ' + error.message);
                throw error;
            });

      } else {
        alert("Please connect with internet")
      }
    });
    return result; // Return the response
 }

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 2020-12-27
    • 2020-10-29
    • 2021-02-02
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多