首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果API调用中不存在数据,我如何忽略它?

如果API调用中不存在数据,我如何忽略它?
EN

Stack Overflow用户
提问于 2021-05-17 02:48:49
回答 1查看 43关注 0票数 0

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

是否可以在我命名为setPokemonuseState钩子中创建一条if语句

如果是这样,我该如何做到这一点,或者我该如何度过这一切?

代码语言:javascript
复制
 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;
EN

回答 1

Stack Overflow用户

发布于 2021-05-17 03:22:22

如果我们首先看一下您的错误,您的响应数据中的api类型数组的索引1是未定义的。因此,当您尝试访问时,它会抛出。

当您不确定应用程序接口的响应时,您可以组合使用optional chaining和为该属性设置默认值。这样,您的代码就不会崩溃。

在您的示例中,我相信您可以这样做:

代码语言:javascript
复制
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 (??)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67560389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档