React/Javascript - TypeError: Cannot read properties of undefined (reading 'json')

React/Javascript - TypeError: Cannot read properties of undefined (reading 'json')

React 和 Javascript 新手,我正在尝试构建我的第一个 React 项目。我想要做的是有一个按钮可以自动获取我在游戏中玩的最后一场比赛。我正在使用 API,当正确调用时,returns 这个 json:

{data: 
       [{id: 0, internal_id: "_map_id_halo1_pillar_of_autumn", name: "The Pillar Of Autumn"},
…]}

我想提取每个数据对象的名称并在按钮下方显示一个无序列表。

但是当我点击按钮时,浏览器显示错误:

TypeError: 无法读取未定义的属性(读取 'json')

执行我提到的代码如下:

async fetchHaloMaps()
    {
        const url = 'https://cryptum.halodotapi.com/games/hmcc/metadata/maps'
        const mapNames = [];

        fetch(url, {
            "method": 'GET',
            "headers": {
                        'Content-Type': 'application/json',
                        'Cryptum-API-Version': '2.3-alpha',
                        'Authorization': 'Cryptum-Token XXX'
                     }
        })
        .then(response => {
            console.log(response);
            if (!response.ok)
                throw new Error("Response not ok!");
        })
        .then(response => 
            response.json())
        .then(data => {
                    
            const i=0;
             for (const d of data)
            {
                mapNames[i] = d.name;
                i++;
            }

            this.setState((state, props) => ({
                numberOfMaps : i
            }));
        })  
        .catch(error => {
            console.log("There was an error: " + error);
        });
    }

我认为我以错误的方式“解析”了 JSON。但在 JSON 中,数据确实是一个具有“名称”属性的数组。所以我想循环数据数组并复制属性“名称”,但是上面的代码不起作用。 我知道使用 fetch 的 HTTP 请求确实成功了,因为在 console.log 中我可以看到响应对象并且它有 200 OK 字段,而且我可以看到与浏览器开发人员工具关联的 JSON。

你没有return来自这个.then的任何东西:

    .then(response => {
        console.log(response);
        if (!response.ok)
            throw new Error("Response not ok!");
    })

所以没有值传递给下一个 .then

虽然您 可以return response,但更好的方法是完全删除中间 .then - 只插入一个 .then你需要等待一些异步的东西。当你得到响应时,你可以检查它是否可以 然后 return .json(),中间没有等待。

.then(response => {
    if (!response.ok) {
        throw new Error("Response not ok!");
    }
    return response.json();
})
.then(data => {