【问题标题】:find function returning undefined from API call查找从 API 调用返回未定义的函数
【发布时间】:2020-06-21 20:31:11
【问题描述】:

我有一个传入 ID 的函数,该函数获取不支持按特定 ID 进行搜索的 API,因此我正在尝试构建一个查找函数来搜索 ID 并返回它。

我以前做过这项工作,但我将函数移动到它们自己的文件中,似乎传递值可能破坏了函数?我没有从函数中得到任何错误,但也许我写的 find 函数不正确?

import React from 'react'

export const fetchHeroDetail = async (id) => {
    const data = await fetch(`https://api.opendota.com/api/heroStats`)
    const heroDetails = await data.json()
    console.log(id)
    console.log(heroDetails)
    console.log(heroDetails.find(heroDetail => id === heroDetail.id))
    return heroDetails.find(heroDetail => id === heroDetail.id)


};

【问题讨论】:

  • 我看不出有什么本质上的错误,但是,通过查看console.log(id)console.log(heroDetails) 的结果应该很容易查明问题。
  • 两人都吐出了自己认为的东西。 id = 我点击的任何英雄, heroDetails 返回英雄的完整对象

标签: reactjs api fetch react-hooks


【解决方案1】:

所以基本上我需要做的就是将 id 转换为字符串中的数字。我刚刚完成了这项工作

return heroDetails.find(heroDetail => heroDetail.id === +id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2015-07-02
    • 1970-01-01
    • 2012-01-15
    相关资源
    最近更新 更多