为什么在fetch函数中匹配未定义



我使用match来提取一个ID,该ID将在API中搜索该ID并从中提取数据。这一直有效,直到我开始四处移动文件,现在我不知道如何将match传递到我的获取函数

HeroDetail.services

import React from 'react'
export const fetchHeroDetail = async ({match}) => {
const data = await fetch(`https://api.opendota.com/api/heroStats`)
const item = await data.json()
const heroId = match.params.id
console.log(match.params.id)
const hero = item.find(element => element.id === Number(heroId))
console.log(hero)
return await hero
};

HeroDetail组件

import React, {useState, useEffect} from "react"
import "../App.css"
import {fetchHeroDetail} from './services/HeroDetail.services'
const setHeroDetail = async setHero => {
const hero = await fetchHeroDetail()
setHero(hero)
}
function HeroDetail() {
const [hero, setHero] = useState({})
useEffect(() => {
setHeroDetail(setHero)
},[])


return(
<div>
<h1>{hero.localized_name} </h1>
<h2>{hero.move_speed}</h2>
<h2>{hero.base_health}</h2>
</div>
)
}
export default HeroDetail

您应该这样做:

function HeroDetail() {
const [hero, setHero] = useState({})
useEffect(async () => {
if (!hero) {
const data = await fetchHeroDetail()
setHero(data)
}
})
...
}

相关内容

  • 没有找到相关文章

最新更新