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

Next.js+TS加载模拟数据时遇TypeError: fake.map is not a function求助

解决TypeError: fake.map is not a function问题

这个错误的核心原因很明确:你拿到的fake不是数组,而是一个包含数组的对象。dummyjson.com/products的返回结构不是直接的产品数组,而是一个包含products数组、total、skip、limit字段的对象,直接对这个对象调用map自然会报错——对象没有map方法。

修复步骤

  1. 先确认接口返回结构
    该接口的返回示例如下:
{
  "products": [
    {"id":1,"title":"iPhone 9",...},
    {"id":2,"title":"iPhone X",...}
  ],
  "total": 100,
  "skip": 0,
  "limit": 30
}
  1. 修改fetch逻辑,提取数组部分
    在你的page.tsx里,需要从响应数据中取出products数组再赋值给fake:
// page.tsx
async function fetchProducts() {
  const res = await fetch('https://dummyjson.com/products');
  // 先解析整个响应对象
  const responseData = await res.json();
  // 提取products数组返回
  return responseData.products;
}

export default async function ProductsPage() {
  const fake = await fetchProducts();
  return (
    <div className="products-list">
      {fake.map(product => (
        <div key={product.id} className="product-item">
          <h3>{product.title}</h3>
          <p>价格: ${product.price}</p>
        </div>
      ))}
    </div>
  );
}
  1. 同步TypeScript类型定义
    确保你的typings.d.ts里的类型能匹配接口返回,比如:
// typings.d.ts
export interface Product {
  id: number;
  title: string;
  price: number;
  // 根据需要添加其他字段,比如description、category等
}

// 定义整个响应的类型
export interface ProductApiResponse {
  products: Product[];
  total: number;
  skip: number;
  limit: number;
}

然后在fetch时加上类型断言,让TypeScript更安全:

async function fetchProducts() {
  const res = await fetch('https://dummyjson.com/products');
  const responseData = await res.json() as ProductApiResponse;
  return responseData.products;
}

常见误区提醒

很多人会忽略接口返回的结构,想当然认为返回的是纯数组。遇到这类map is not a function错误,第一时间打印console.log(fake)看看实际拿到的数据是什么类型,就能快速定位问题。

内容的提问来源于stack exchange,提问作者Captai-N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:45:10