首页 > 解决方案 > 反应中异步函数的结果未准备好返回元素

问题描述

我正在做一个需要在 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

是这样吗?我在这里遗漏了什么明显的东西吗?

标签: javascriptreactjs

解决方案


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.


推荐阅读