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