SvelteKit 加载函数中的空参数

Empty parameters in SvelteKit load function

提问人:ShashComandur 提问时间:10/21/2023 更新时间:10/21/2023 访问量:47

问:

我正在尝试按照 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 对象为空。paramsparams.id+page.server.js'as-lost'console.log(JSON.stringify(data))

我在这里做错了什么?我尝试在每一步都按照教程进行操作,但它仍然不起作用。请帮忙。

javascript 参数传递 svelte

评论


答:

2赞 H.B. 10/21/2023 #1

如果在路由路径中使用,则还必须使用 .
(也许让它成为单数)
[collections]params.collections

评论

0赞 ShashComandur 10/21/2023
我把头撞在墙上,试图弄清楚这个问题一个小时!非常感谢!
1赞 H.B. 10/21/2023
建议使用调试器,然后只需检查范围内的所有对象。(您可以使用侧面的复选标记轮廓接受答案。