[英]Fetch react native get data out of the function
I'm trying to make a fetch function that return the data like a classic function. 我正在尝试使获取函数像经典函数一样返回数据。 like this :
像这样 :
function fetchGetData(idUser){
fetch('url?idU='+idUser)
.then((response)=>console.log(response))
.then((responseText)=>{
if(responseText.result!='true'){
console.log(responseText)
return parseInt(responseText) // return the data (a number for me)
}
else {
return 0 ;
}
});
}
then I want to use the function like this : var data = fetchGetData(id); 然后我想使用这样的功能:var data = fetchGetData(id); I'm new on react, I don't know if its possible.
我是新来的反应者,不知道是否可能。 In my context, i can't use states to save it in the function.
在我的上下文中,我不能使用状态将其保存在函数中。 Any ideas?
有任何想法吗? Thank you
谢谢
Because you want to asgin response of the request to a vaiable like a sync function response ( var data = fetchGetData(id);
), It's better to use async/await for this case. 因为您希望将请求的响应像同步函数响应一样(
var data = fetchGetData(id);
) var data = fetchGetData(id);
,所以在这种情况下最好使用async / await 。 It's your rewritten fetchGetData: 这是您重写的fetchGetData:
async function fetchGetData(idUser){
try {
let response = await fetch('url?idU='+idUser);
console.log(response);
let responseText = await response; // are you sure it's not response.json();?
if(responseText.result!='true'){
console.log(responseText);
return parseInt(responseText) // return the data (a number for me)
} else {
return 0 ;
}
} catch(error) {
console.error(error);
}
}
Now you can assign it's returned value by calling the function: 现在,您可以通过调用函数来分配其返回值:
var data = await fetchGetData(id);
In this way, you are using async actions link sync actions. 这样,您正在使用异步操作链接同步操作。
If expected response is JSON
, chain .json()
to response
to return javascript
object, else use .text()
to return response as plain text 如果预期的响应是
JSON
,则将.json()
到response
以返回javascript
对象,否则使用.text()
以纯文本形式返回响应
function fetchGetData(idUser) {
return fetch('url?idU=' + idUser) // note `return` fetch from function call
.then(response => {
return response.text() // if `response` is `JSON` use `.json()` here
})
.then(responseText => {
// if (responseText.result != 'true') { // is expected response `JSON` or text?
console.log(responseText);
return parseInt(responseText) // return the data (a number for me)
// } else {
// return 0;
// }
})
.catch(err => Promise.reject(err))
}
I had a similar problem.. use _bodyText
properties 我有一个类似的问题..使用
_bodyText
属性
function fetchGetData(idUser){
fetch('url?idU='+idUser)
.then((response)=>{console.log(response._bodyText)
return parseInt(response._bodyText)})
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.