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

Astro页面自动为Service组件加载多MD内容报错:title未定义

解决Astro组件“title未定义”错误及内容自动注入方案

1. 核心问题分析

出现“title未定义”错误的原因有两个:

  • Service组件未显式声明接收外部传递的props
  • 页面中访问内容集合的Frontmatter字段时路径错误(Astro 2.x+中,集合项的Frontmatter数据存放在data子属性下)

2. 修正Service组件

组件无需嵌套Layout(页面已统一使用Layout),只需显式声明接收的props并渲染内容:

---
// 显式声明要接收的属性
export let title: string;
export let price: string;
export let description: string;
---

<div>
    <h2>{title}</h2>
    <p>{price}</p>
</div>
<p>{description}</p>

3. 修正页面代码

调整内容集合字段的访问路径,确保正确获取Frontmatter数据:

---
import Layout from '../layouts/Layout.astro';
import { getCollection } from "astro:content";
const allPosts = await getCollection("posts");
import Service from "../components/Service.astro";
---

<Layout title="Serwis">
    <ul>
        {
             allPosts.map((post, index) => (
                <Service 
                    key={index} 
                    title={post.data.title} 
                    price={post.data.price} 
                    description={post.data.description}
                />
            ))
          }
    </ul>
</Layout>

4. 额外检查项

  • 确认src/content/posts目录下存在post1.md、post2.md文件
  • 每个md文件的Frontmatter(---包裹区域)必须包含title、price、description三个字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 22:08:26