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

shadcn UI+JSON Server数据渲染异常:仅显示单张卡片且内容错误

问题排查与修复方案

1. 确认JSON数据的获取与格式

首先检查请求返回的数据是否为数组类型:

  • 如果你的_data/db.json是嵌套结构(比如{"recipes": [...]}),需请求http://localhost:3000/recipes才能拿到数组;若直接请求根路径/,得到的是包含数组的对象,遍历对象只会渲染一张卡片。
  • 修正fetch逻辑,确保拿到数组:
async function getRecipes() {
  const res = await fetch('http://localhost:3000/recipes');
  const data = await res.json();
  // 兜底处理:若返回的是对象,取出数组字段
  return Array.isArray(data) ? data : data.recipes;
}

2. 检查循环渲染逻辑

若仅显示单张卡片,大概率是未用map遍历数组,而是直接取了第一个元素:

错误示例

export default async function Page() {
  const recipes = await getRecipes();
  return (
    <div className="grid gap-4">
      {/* 仅渲染第一个元素,未遍历整个数组 */}
      <RecipeCard recipe={recipes[0]} />
    </div>
  );
}

正确写法

export default async function Page() {
  const recipes = await getRecipes();
  return (
    <div className="grid grid-cols-3 gap-4">
      {/* 用map遍历数组,必须加唯一key(优先用id) */}
      {recipes.map((recipe) => (
        <RecipeCard key={recipe.id} recipe={recipe} />
      ))}
    </div>
  );
}

注意:未加key会导致React复用组件,可能引发首张卡片数据展示异常。

3. 检查卡片组件的数据绑定

首张卡片详情不显示,通常是组件内用了错误的属性名(比如JSON里是title,代码里写了name):

错误示例

function RecipeCard({ recipe }) {
  return (
    <div className="p-4 border rounded">
      <h3>{recipe.name}</h3> {/* JSON字段是title,此处写错 */}
      <p>{recipe.time}分钟</p> {/* JSON字段是duration,此处写错 */}
    </div>
  );
}

正确写法

function RecipeCard({ recipe }) {
  return (
    <div className="p-4 border rounded">
      <h3>{recipe.title}</h3>
      <p>{recipe.duration}分钟</p>
    </div>
  );
}

4. 验证JSON Server返回数据

在浏览器直接访问http://localhost:3000/recipes,确认返回的是包含title、duration等字段的数组。若返回异常,检查db.json结构:

正确的db.json结构(数组形式)

[
  { "id": 1, "title": "Recipe1", "duration": 10 },
  { "id": 2, "title": "Recipe2", "duration": 15 }
]

或嵌套结构(对应请求路径/recipes)

{
  "recipes": [
    { "id": 1, "title": "Recipe1", "duration": 10 },
    { "id": 2, "title": "Recipe2", "duration": 15 }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:30:12