Fetch React本机从功能中获取数据



我正在尝试制作一个像经典函数一样返回数据的fetch函数。这样:

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

然后我想使用这样的函数:var data = fetchgetData(id(;我是新来的React,我不知道是否可能。在我的上下文中,我无法使用状态将其保存在功能中。有任何想法吗?谢谢

,因为您想将请求的响应asgin响应,例如同步函数响应(var data = fetchGetData(id);(,所以最好使用async/等待这种情况。这是您重写的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);
  }
}

现在您可以通过调用函数来分配返回的值:

var data = await fetchGetData(id);

以这种方式,您正在使用异步操作链接链接同步操作。

如果预期响应是 JSON,链 .json() to 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))
}

我也有类似的问题。使用 _bodyText properties

function fetchGetData(idUser){
        fetch('url?idU='+idUser)
        .then((response)=>{console.log(response._bodyText)
              return parseInt(response._bodyText)})
        );
    }

最新更新