javascript - 使用 "nested"获取设置钩子(Hook)时,React、Axios、PokeAPI 返回未定义

标签 javascript reactjs axios react-hooks

我尝试做一个小项目,制作一个迷你 Pokedex,以更加熟悉 hooks 和 Axios。我正在尝试传递 PokeAPI 给出的 Pokemon 的 URL,以便让 Pokemon 对象数组显示其所有信息。这是我现在的代码,但它返回一个包含 20 个“未定义”元素的数组。

const [pokemon, setPokemone] = useState([]);

axios.get('https://pokeapi.co/api/v2/pokemon/')
  .then(res => {
    setPokemon(res.data.results.map(p => {
      axios.get(p.url)
        .then(res => res.data);
    }));
  });

我能做什么,或者我做错了什么?如果我console.log“res.data”,它会打印所有对象,但由于某种原因,该信息未设置。

预先感谢您的任何帮助/建议。

最佳答案

map 函数返回一个新值数组,您的函数不返回任何内容(您实现的回调函数包装在 {} 中,没有 return) 所以它默认为 undefined

您应该首先获取神奇宝贝列表,然后获取每个神奇宝贝的详细信息,然后在完成后绘制 map 并设置值

axios
  .get("https://pokeapi.co/api/v2/pokemon/")
  .then((res) => {
    return res.data.results
  })
  .then((results) => {
    return Promise.all(results.map((res) => axios.get(res.url)))
  })
  .then((results) => {
    setPokemon(results.map((res) => res.data))
  })

下面的 Codesandbox 演示

Edit ecstatic-swanson-e6bkt

关于javascript - 使用 "nested"获取设置钩子(Hook)时,React、Axios、PokeAPI 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63422054/

相关文章:

javascript - 如何检查三元运算符中的 undefined variable ?

javascript - 我应该声明什么值类型的对象变量

javascript - 如何在 React 中使用 Material UI 定义背景图像来填充屏幕并删除左侧和右侧的边缘?

reactjs - 使用 React、Redux 和 Axios 处理异步请求?

javascript - axios Post请求没有React功能

javascript - 为 cookie 设置一个新值会创建一个重复的 cookie - jquery cookie

javascript - 无法在 Javascript 中使用 getAttribute() 从表中检索数据

javascript - 重置 React 中控件的默认值

javascript - 看不到我使用 React-dnd 拖动的项目

javascript - $request->ajax() 在 ajax 调用时返回 false