如果我进行这个调用,但是我输入的pokemon没有第二个类型,我会收到这个错误消息:

是否可以在我命名为setPokemon的useState钩子中创建一条if语句
如果是这样,我该如何做到这一点,或者我该如何度过这一切?
import Axios from "axios";
import React, { useState } from "react";
import "./SearchPokemon.css";
function PK() {
const api = Axios.create({
baseURL: "https://pokeapi.co/api/v2/",
});
const [pokemon, setPokemon] = useState({});
const [pokemonDescription, fetchDescription] = useState({});
const [evolution, pokemonEvolution] = useState({});
const searchPokemon = () => {
api.get(`pokemon/charmander`).then((response) => {
setPokemon({
name: response.data.name,
height: response.data.height,
weight: response.data.weight,
img: response.data.sprites.front_default,
id: response.data.id,
type: response.data.types[0].type.name,
type2: response.data.types[1].type.name,
});
api.get(`pokemon-species/${response.data.id}/`).then((response) => {
fetchDescription({
entry: response.data.flavor_text_entries[0].flavor_text,
evolution: response.data.evolution_chain.url,
});
api.get(`${response.data.evolution_chain.url}`).then((response) => {
pokemonEvolution({
evolution: response.data.chain.evolves_to[0].species.name,
});
});
});
});
};
return (
<div>
<div className="main">
<h1 style={{ textTransform: "capitalize" }}>{pokemon.name}</h1>
<h1>No. {pokemon.id}</h1>
<img src={pokemon.img} alt="" />
</div>
<div className="info">
<h3 style={{ textTransform: "capitalize" }}>
Type: {pokemon.type} {pokemon.type2}
</h3>
<h3>Height: {pokemon.height * 10} Cm</h3>
<h3>Weight: {pokemon.weight / 10} Kg</h3>
</div>
<div className="desc">
<div className="desc-info">
<h3 style={{ textTransform: "capitalize" }}>
{pokemonDescription.entry}
</h3>
</div>
</div>
<h1 style={{ textTransform: "capitalize" }}>
Evolution: {evolution.evolution}
</h1>
<button onClick={searchPokemon}>Click me</button>
</div>
);
}
export default PK;发布于 2021-05-17 03:22:22
如果我们首先看一下您的错误,您的响应数据中的api类型数组的索引1是未定义的。因此,当您尝试访问时,它会抛出。
当您不确定应用程序接口的响应时,您可以组合使用optional chaining和为该属性设置默认值。这样,您的代码就不会崩溃。
在您的示例中,我相信您可以这样做:
const response = {
data: {
types: []
}
};
console.log(response.data.types[1]?.type.name ?? "pick a value or leave an empty string");
// type2: response.data.types[1]?.type.name ?? ""
注意我在期望类型数组的索引1后面添加的问号。此符号允许可选的链接。
然后我们使用Nullish coalescing operator (??)。
https://stackoverflow.com/questions/67560389
复制相似问题