![](/img/trans.png)
[英]RTK useLazyQuery always making calls to the API even when called with same params on multiple components
[英]Restful API failing sporadically but “catch” statement is always called, even when it does not fail
我們正在使用寧靜的 API 來檢索有關正在播放的電子競技比賽的信息。 有時頁面只是加載,沒有從 API 返回任何信息。
我相當有信心問題出在 API 本身,但想再次檢查我們沒有做錯任何事情。 請參閱下面的代碼:
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "http://datafeed.bet/en/esports.json ";
fetch(proxyurl + url)
.then(response => response.json())
.then(data => {
const list = data;
const games =
list &&
list.Sport &&
list.Sport.Events &&
list.Sport.Events.map((match) =>
match.Name.substr(0, match.Name.indexOf(","))
);
const uniqueGames = [...new Set(games)];
let combinedMatches = [];
data &&
data.Sport &&
data.Sport.Events &&
data.Sport.Events.map((game) => {
game.Matches.map((match) => {
match.Logo = game.Logo;
match.TournamentName = game.Name;
match.CategoryID = game.CategoryID;
match.ID = game.ID;
});
combinedMatches = combinedMatches.concat(game.Matches);
});
this.setState({
gameData: data,
games: games,
uniqueGames: uniqueGames,
preloading: false,
filteredGames: combinedMatches,
allMatches: combinedMatches,
count: Math.ceil(combinedMatches.length / this.state.pageSize),
});
var i;
let allMatches = 0;
let temp;
for (i = 0; i < this.state.filteredGames.length; i++) {
temp = allMatches =
allMatches + this.state.filteredGames[i].Matches.length;
}
this.setState({ allMatches: allMatches });
})
.catch(console.log('error');
讓我感到困惑的是,無論是否返回數據,都會調用“catch”語句,將“錯誤”輸出到控制台。 我想為不返回數據時構建一些解決方法。 這會放在“catch”語句中嗎? 如果是這樣,為什么只有在操作實際失敗時才讓 catch 運行。
當你這樣做時:
.catch(console.log('error'))
您立即調用console.log('error')
並將其結果( undefined
)傳遞給catch
。 在這種情況下,它會立即調用它,甚至在執行 AJAX 操作之前。
您要傳遞給catch
的是 function ,如果/當它需要時,它將調用該操作:
.catch(e => console.log('error'))
順便說一句,您可能還想記錄錯誤本身,以便查看發生了什么,而不僅僅是字符串'error'
:
.catch(e => console.log('error', e))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.