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

NextJS使用react-query遍历数据报错:map不存在于Response类型

解决React Query中Property 'map' does not exist on type 'Response'的问题

问题根源

你的GetAlphabet方法返回的是原始的Response对象,而非解析后的JSON数组。fetch API调用后仅返回Response实例,必须手动调用.json()方法才能获取实际的数组数据,因此data的类型是Response,自然没有map方法。

解决方案

1. 修改API服务方法,解析JSON并处理错误

更新GetAlphabet方法,添加JSON解析步骤,并在请求失败时抛出错误(而非返回Response):

// 确保导入Alphabet接口到该文件
import type { Alphabet } from '../path-to-your-interface-file';

async GetAlphabet(): Promise<Alphabet[]> {
  try {
    const response = await fetch('/api/character');
    if (!response.ok) {
      // HTTP状态码非2xx时抛出错误
      throw new Error('Failed to retrieve the alphabet characters');
    }
    // 解析响应为JSON数组并返回
    return await response.json();
  } catch (error) {
    // 抛出错误,让React Query捕获并设置error状态
    throw new Error('Failed to retrieve the alphabet characters');
  }
}

2. 优化Page组件的状态处理

在组件中添加错误状态的显示,同时简化逻辑:

"use client"

import { useQuery } from "@tanstack/react-query";
import ApiService from "../../../services/api";

interface Alphabet {
  id: number;
  name: string;
  typeId: number;
  languageId: number;
  language: {
    id: number;
    name: string;
  };
  type: {
    id: number;
    name: string;
  }
}

export default function Page() {
  const { isLoading, data, error } = useQuery({ 
    queryKey: ['alphabet'], 
    queryFn: () => ApiService.GetAlphabet() 
  })

  if (isLoading) {
    return <div>Loading...</div>
  }

  if (error) {
    return <div>Error: {(error as Error).message}</div>
  }

  return (
    <>
      <h1>Korean alphabet</h1>
      <ul className="flex gap-1 text-4xl">
        {data?.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </>
  )
}

为什么之前的尝试无效?

你之前检查data是否为数组但列表未显示,是因为data实际是Response对象而非数组,因此data?.map不会执行。修改API方法后,data会变为解析后的JSON数组,即可正常渲染列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:10:03