【发布时间】: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 => 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