javascript - 反应中异步函数的结果未准备好返回元素
问题描述
我正在做一个需要在 React 中调用 aync API 的个人项目
我进行 API 调用,等待承诺,将其解析为 JSON 并继续前进:
const getMatch = async (matchId) => {
const response = await fetch(
`https://cors-anywhere.herokuapp.com/https://euw1.api.riotgames.com/lol/match/v4/matches/${matchId}?api_key=${API_KEY}`
);
const data = await response.json();
return data;
};
然后我循环遍历 JSON 寻找一个条件,该条件返回一个真或假,以便三元可以将一个类应用到一个 html 元素,这里是循环:
const didWin = async () => {
var m = await getMatch(match.gameId);
var pId, tId;
for (var p in m.participantIdentities) {
if (m.participantIdentities.hasOwnProperty(p)) {
if (m.participantIdentities[p].player.summonerName == profileName) {
pId = m.participantIdentities[p].participantId;
}
}
}
for (var x in m.participants) {
if (m.participants.hasOwnProperty(x)) {
if (m.participants[x].participantId == pId) {
tId = m.participants[x].teamId;
}
}
}
for (var t in m.teams) {
if (m.teams.hasOwnProperty(t)) {
if (m.teams[t].teamId == tId && m.teams[t].win == "Win") {
console.log(true);
return true;
}
}
}
console.log(false);
return false;
};
这里可以看到上面的函数被调用并根据返回应用一个类:
<div className={`card-footer ${didWin() ? "bg-success" : "bg-danger"}`}>
然而,在测试了这个反应组件的每一次调用之后,总是等同于 true,这不应该是这种情况,并且在大多数情况下应该是 50/50 true false
对我来说,感觉好像didWin()
没有时间在反应返回给定的 html 元素之前完成检查,默认调用为 true
是这样吗?我在这里遗漏了什么明显的东西吗?
解决方案
You can create a variable like won = false
and then change the variable value inside didWin method, this way you won't have a promised returned, and you will be reading a boolean value.
推荐阅读
- com - 释放COM接口的正确方法
- javascript - 页面重定向后如何打开jquery ui模式
- winforms - 当 JavaScript 处理 OnBeforeUnload 时,如何使用 CefSharp 显示自定义消息?
- ios - 如何以编程方式从 samba 下载文件夹?
- grails - 如何在 urlmappings 文件中映射 500 错误?
- android - android 和 ios 的 React Native 指纹认证
- docker - 将 python 项目添加到 docker 中并在 jupyter notebook 中进行测试
- ios - 如何更改 UITextField 中的密码屏蔽时间?或者它有一个默认行为
- python - Django删除确认视图显示变量名而不是信息
- python - Pandas 无法识别 csv 文件中的 datetimeindex