【问题标题】:Getting TypeError: _ is undefined when trying to access data that comes from an API尝试访问来自 API 的数据时出现 TypeError:_ 未定义
【发布时间】:2021-05-06 23:46:47
【问题描述】:

我使用这个 useState 挂钩在其中存储一个 JSON 数组。

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

我通过这个 useEffect 挂钩从 API 获取数据

useEffect(async () => {
    const fetchPokemonData = async () => {
        setLoading(true);
        const pokemonDetails = await axios.get(`https://pokeapi.co/api/v2/pokemon-species/${match.params.id}`);
        setPokemon(pokemonDetails.data);
        setLoading(false);
    };
    
    fetchPokemonData();
}, [match])

那我尝试通过这个显示一条数据

<section id="pokemon-info" className="bg-info text-center px-5 col-md-12 col-lg-6 flex-fill">
            <h1>{pokemon.name}({pokemon.names[0].name})</h1></section>

它有时会起作用,但有时会出错

TypeError: pokemon.names is undefined

我假设它与尚未加载的数据有关。 我从这个 API 端点 https://pokeapi.co/api/v2/pokemon/ 获取数据

【问题讨论】:

  • 在异步函数中添加try-catch。
  • 我已经尝试添加一个try catch函数,它仍然不起作用。

标签: reactjs


【解决方案1】:

你的口袋妖怪在pokemon.data.results里面。

检查这个例子:

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

function App() {
  const [pokemon, setPokemon] = useState([]);

  const fetchPokemonData = async () => {
    const pokemonDetails = await axios.get(
      `https://pokeapi.co/api/v2/pokemon/`
    );
    setPokemon(pokemonDetails.data.results[0].name);
    console.log(pokemonDetails.data.results);
  };

  useEffect(() => {
    fetchPokemonData();
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <section
          id="pokemon-info"
          className="bg-info text-center px-5 col-md-12 col-lg-6 flex-fill"
        >
          <h1>{pokemon}</h1>
        </section>
      </header>
    </div>
  );
}


【讨论】:

  • 我刚刚尝试过,不幸的是没有解决它。
  • 如果我的问题不好,我很抱歉。我正在做的是通过在 url 中添加他们的 id 号来获得特定的 pokemon。我从 API 获取时没有结果。
【解决方案2】:

问题是当 React 尝试渲染组件时 pokemon.names 仍然未定义,因此出现错误。 API 在获取数据时包含的任何对象数组都会发生这种情况。我通过首先检查数据是否可访问来解决问题。所以,

<h1>{pokemon.name}({pokemon.names[0].name})</h1>

变成

<h1>{pokemon.name}({pokemon.names && pokemon.names[0].name})</h1>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2016-10-08
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多