我正在尝试按照 SvelteKit 教程 在 SvelteKit 中构建一个艺术作品集。我有一个名为
art/
的页面,其中有一个名为 [collections]/
的子目录,用于存放各种不同的艺术作品收藏。
我暂时从名为
data.js
的文件加载数据,该文件具有以下结构:
export const collections = [
{
title: 'Crisis Vision',
id: 'crisis-vision',
content: '<p>crisis vision content</p>'
},
{
title: 'From the Garden',
id: 'from-the-garden',
content: '<p>from the garden content</p>'
},
{
title: 'As Lost Through Collision',
id: 'as-lost',
content: '<p>as lost content</p>'
}
];
+page.server.js
中的[collections]/
文件包含以下内容:
import { error } from '@sveltejs/kit';
import { collections } from '../data.js';
export function load( {params} ) {
const ret = collections.find((c) => c.id === params.id);
return {
ret
};
}
+page.svelte
文件包含以下内容:
<script>
export let data;
console.log(JSON.stringify(data))
</script>
<h1>{data.ret.title}</h1>
<div>{@html data.ret.content}</div>
当我尝试运行此程序时,我得到
TypeError: Cannot read properties of undefined (reading 'title')
。
我相信我已经将范围缩小到
params
变量。当我在 params.id
文件中取出 +page.server.js
并直接将其替换为数据中的示例(例如 'as-lost'
)时,它会按预期工作 (当然,每个集合都显示相同的内容)。当我将 console.log(JSON.stringify(data))
添加到页面文件的脚本部分时,它显示 params 对象为空。
我在这里做错了什么?我已经尝试按照教程的每一步进行操作,但仍然不起作用。请帮忙。
如果您在路线路径中使用
[collections]
,则还必须使用params.collections
。