【发布时间】: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