【问题标题】:How to get specific data out of an API using the URL如何使用 URL 从 API 中获取特定数据
【发布时间】:2020-03-03 05:13:04
【问题描述】:

这可能是一个简单的解决方案,但我无法看到解决方案。我花费了太多时间的项目终于开始关闭,但是我已经接近尾声了,我正在使用的 API 出现问题。

我希望每当我在 HeroDetail 中使用我的比赛时,我将能够使用该 ID 来定位我想要在您点击它时显示的英雄的谁数据。我的其他组件完全按照我认为的方式工作。他们使用特定于我单击的英雄的 ID 将我引导到我的 HeroDetail 页面。

我遇到的问题是,使用此 API,我不知道如何使用该 ID 来提取该特定 ID 的 heroStats。

我认为我可以在 URL 的末尾添加一些参数,例如 ?_id=${},但没有成功。 API URL 是https://docs.opendota.com/#section/Introduction,如果您也想了解一下它。我找不到任何可以帮助我的东西。

import React, {useState, useEffect} from "react";
import "./App.css";


function HeroDetail({match}) {

    useEffect(() => {
        fetchHero();
        console.log(match)
    },[]);

    const [item, setItem] = useState([]);

    const fetchHero = async () => {
        const fetchHero = await fetch(`https://api.opendota.com/api/heroStats}`);
        const item = await fetchHero.json();
        setItem(item);
        console.log(item)
    };
    return(
        <div>
           <h1>{item.id} </h1>
        </div>
    );
}

export default HeroDetail;

【问题讨论】:

  • 你可以试试const hero = item.find(h =&gt; h.id === /* the id of the hero you want */)
  • const hero = item.find(h => h.id === match.params.id) 给我未定义
  • 你从fetch()得到的数据中是否有id为match.params.id的英雄?
  • 如果您从生产代码中复制粘贴了上述代码 sn-p,可能值得注意的是,您的提取 URL 中有一个尾随 '}'
  • 蒂姆的方法应该会给你合适的英雄。您能否确认match.params.id 的类型确实是数字而不是字符串?

标签: javascript reactjs api fetch


【解决方案1】:

我拼凑了一个小的 CodeSandBox,其中包含我在 OP cmets 中讨论的工作示例。

https://codesandbox.io/s/silent-leftpad-cbjb3?fontsize=14&hidenavigation=1&theme=dark

【讨论】:

  • const heroId = match.params.id; const hero = item.find(element =&gt; element.id === heroId); console.log(hero); 仍然给我未定义
  • match.params.id 未定义吗?
  • 不,我有另一个组件来映射所有英雄,关键是他们的 id,一旦我点击我想选择的英雄,它就会将该 ID 添加到 url,这就是 match.params。身份证返回。所以在这种情况下,我选择了 Bloodseeker 并返回了 4
  • github.com/kevin6767/api_search 如果你想检查一切
  • 没有package.json?
【解决方案2】:

Opendota 不提供通过 id 检索 HeroStat 的 API。但是您只能获取一次 HeroStats。将它们存储到您的商店中(如果您使用的是 Redux)。使用 filterfind 来获取带有您的 ID 的准确 heroStat。此外,您可以使用reselect 创建记忆选择器。

【讨论】:

    【解决方案3】:

    作为API文档,我们可以看到它会给出一个对象数组。

    [ { “身份证”:0, “名称”:“字符串”, "localized_name": "字符串", “img”:“字符串”, “图标”:“字符串”, “亲赢”:0, “pro_pick”:0, “hero_id”:0, “pro_ban”:0, “1_pick”:0, “1_win”:0, “2_pick”:0, “2_win”:0, “3_pick”:0, “3_win”:0, “4_pick”:0, “4_win”:0, “5_pick”:0, “5_win”:0, “6_pick”:0, “6_win”:0, “7_pick”:0, “7_win”:0 } ]

    所以,如果您想访问 id,那么在您的情况下, item[0].id 会起作用,或者你可以使用 find

    const found = item.find(element => element.id == 'whatever id');

    console.log(找到);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多