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

Next 13服务组件使用map遍历数组时出现TypeScript错误

解决TypeScript错误:Property 'map' does not exist on type '{ item: Item[]; }'

问题原因

  1. 查询返回结构不符预期:fetchItems中prisma.restaurant.findUnique的返回值是一个包含item数组的对象(类型为{ item: Item[] } | null),你直接对这个对象调用map方法,自然触发类型错误。
  2. 遗漏异步等待:prisma.restaurant.findUnique是异步操作,原代码未添加await,导致fetchItems实际返回的是Promise对象,而非预期的查询结果。

修正后的代码

import { PrismaClient } from "@prisma/client";
import React from "react";
import localStyles from "./../page.module.css";

const prisma = new PrismaClient();

const fetchItems = async (slug: string) => {
  // 添加await获取实际查询结果
  const restaurant = await prisma.restaurant.findUnique({
    where: {
      slug
    },
    select: {
      item: true
    }
  });

  return restaurant;
};

export default async function MenuCard({ slug }: { slug: string }) {
  const restaurant = await fetchItems(slug);
  console.log(restaurant);
  
  return (
    <div className={localStyles.menuItems}>
      {/* 先判断restaurant和item数组是否存在,再调用map */}
      {restaurant?.item?.map((menuItem) => (
        <div className={localStyles.menuCard} key={menuItem.id}>
          <h1>{menuItem.name}</h1>
          <p>A well done steak with lobster and rice</p>
          <b>80.00</b>
        </div>
      ))}
    </div>
  );
}

关键修正点

  • 补全异步等待:在prisma.restaurant.findUnique前添加await,确保拿到实际查询结果而非Promise。
  • 正确访问数组:将变量名改为restaurant(避免与数组元素重名混淆),通过restaurant.item获取真正的数组后再调用map。
  • 安全空值处理:使用restaurant?.item?.map的可选链语法,处理restaurant为null或item不存在的边界情况,避免运行时报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:32:40