在 SvelteKit 中,动态路由文件夹名(如 [collections])会映射为同名的 params 属性;若访问 params.id 但路径段名为 collections,则 params.id 恒为 undefined,导致数据查找失败。
在 sveltekit 中,动态路由文件夹名(如 `[collections]`)会映射为同名的 `params` 属性;若访问 `params.id` 但路径段名为 `collections`,则 `params.id` 恒为 `undefined`,导致数据查找失败。
当你将动态路由目录命名为 [collections]/ 时,SvelteKit 会自动将该路径段的值注入 params.collections,而非 params.id。因此,原始代码中 params.id 始终为 undefined,collections.find(...) 返回 undefined,最终在 +page.svelte 中尝试读取 data.ret.title 时触发 TypeError。
✅ 正确做法是:保持路径段名与 params 键名严格一致。修改 +page.server.js 如下:
// src/routes/art/[collections]/+page.server.js
import { error } from '@sveltejs/kit';
import { collections } from '../data.js';
export function load({ params }) {
// ✅ 正确:使用 params.collections(与文件夹名 [collections] 匹配)
const collection = collections.find((c) => c.id === params.collections);
if (!collection) {
throw error(404, `Collection "${params.collections}" not found`);
}
return { collection };
}
同时更新 +page.svelte,解构更清晰、增强健壮性:
开箱即用的技能链路由引擎。13 条预定义链覆盖搜索、开发、审查、MLOps、法律、创意等场景,三层路由架构(触发词→SAD反馈→DAG编排),recall@10=96.97%。配置驱动(chains.yaml),零代码扩展。pip install skill-weave-chains 一键安装。
<!-- src/routes/art/[collections]/+page.svelte -->
<script>
export let data;
</script><h1>{data.collection.title}</h1>
<div>{@html data.collection.content}</div>
⚠️ 注意事项:
- 动态参数名必须完全匹配方括号内的标识符(区分大小写,不支持别名);
- 强烈建议在 load 函数中添加缺失项校验(如 if (!collection) throw error(404)),避免静默失败;
- 若希望语义更准确(如单个集合),可将文件夹重命名为 [id]/ 或 [slug]/,并同步调整 params.id 访问——这比强行复用 collections 更符合直觉;
- SvelteKit 不会自动将 id 字段注入 params;params 仅包含 URL 路径中动态段的原始字符串值。
总结:SvelteKit 的 params 是路径驱动的键值映射,不是数据模型字段映射。牢记「文件夹名即参数名」这一原则,即可避免绝大多数 undefined 相关错误。










