You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RTK Query与React调用Pokemon API时出现未定义属性读取错误

问题分析与解决方案

错误原因

  • API返回结构不匹配:调用PokeAPI的/pokemon接口时,返回的是包含results数组的对象,而非直接的宝可梦数组,直接对data执行map操作会触发错误。
  • 初始状态未处理:组件初始化阶段data为undefined,此时调用map会引发类型错误。
  • 接口命名语义错误:当前接口用于获取宝可梦列表,却命名为getPokemonByName,易造成逻辑混淆。

修正后的完整实现

1. 调整API定义(pokemonApi.js)

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const pokemonApi = createApi({
  reducerPath: "pokemonApi",
  baseQuery: fetchBaseQuery({
    baseUrl: "https://pokeapi.co/api/v2/",
  }),
  endpoints: (builder) => ({
    // 修正接口名称,语义更准确
    getPokemonList: builder.query({
      query: () => `/pokemon`,
    }),
    // 新增单个宝可梦详情查询接口(用于获取体重、身高、精灵图)
    getPokemonDetail: builder.query({
      query: (nameOrId) => `/pokemon/${nameOrId}`,
    }),
  }),
});       

export const { useGetPokemonListQuery, useGetPokemonDetailQuery } = pokemonApi;
export default pokemonApi;

2. 修正组件逻辑(PokemonCard.jsx)

import React from "react";
import { useGetPokemonListQuery, useGetPokemonDetailQuery } from "../Api/pokemonApi";

function PokemonCard() {
  const { data: pokemonList, error, isLoading, isError } = useGetPokemonListQuery();

  return (
    <>
      <ul>
        {isLoading && <li>...Loading...</li>}
        {isError && <li>{error.message}</li>}
        {/* 先判断数据是否存在,再遍历results数组 */}
        {pokemonList?.results?.map((pokemon) => (
          <PokemonItem key={pokemon.name} name={pokemon.name} />
        ))}
      </ul>
    </>
  );
}

// 拆分出单独的宝可梦项组件,负责获取并展示详情
function PokemonItem({ name }) {
  const { data: pokemon, isLoading: detailLoading } = useGetPokemonDetailQuery(name);

  if (detailLoading) return <li>Loading {name}...</li>;

  return (
    <li style={{ listStyle: 'none', padding: '10px', border: '1px solid #eee', margin: '10px 0', width: '200px' }}>
      <h3>{pokemon.name}</h3>
      <p>身高: {pokemon.height / 10}m</p>
      <p>体重: {pokemon.weight / 10}kg</p>
      <img 
        src={pokemon.sprites.front_default} 
        alt={pokemon.name} 
        style={{ width: '100px', height: '100px' }}
      />
    </li>
  );
}

export default PokemonCard;

3. Store与App组件(无需修改)

你的Store配置和App组件中ApiProvider的使用逻辑是正确的,保持原有代码即可。

内容的提问来源于stack exchange,提问作者Omer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 03:00:05