簡體   English   中英

使用本機獲取數據錯誤

[英]fetch data error with react native

我使用了兩節課,我稱之為第二節課,如下所示

let s = new SearchExtend();

output = s.fetchData(search)
alert(output)

第二個功能:

fetchData = (search) => {

      fetch('http://example.com/search.php' , {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({

          // Getting the search.
          search: search
        })
      }).then((response) => response.json())

       .then((responseJson) => {
             return responseJson;
       })
       .catch((error) => {
         console.error(error);
       });
}

但我進入“警報”未定義

當我使用this.setState而不是return時,出現以下錯誤:

警告setstate(...)只能更新已安裝或正在安裝的組件

您由於使用諾言而變得undefined 最初,它返回未定義的值,一旦解決了諾言,您將獲得實際的數據。

處理此問題的更好方法是返回諾言並按如下方式在外部解決它:

const fetchApi = () => {
   return fetch("https://swapi.co/api/people" , {
    method: 'GET',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    }
  }).then((response) => {
    return response.json();
  })
   .then((responseJson) => {
    return responseJson;
  })
    .catch((error) => {
    console.error(JSON.stringify(error));
  });
}


fetchApi()
.then((data) => {
  console.log("data", data);
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM