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

SvelteKit load()函数导出props后出现未定义错误如何解决?

问题核心原因

SvelteKit中load函数返回的props字段下的所有属性,会作为独立的prop传递给布局/页面组件,不会自动生成一个名为props的聚合变量,你需要在组件的普通<script>标签中显式声明接收这些prop,才能正常使用。


1. 修正__layout.svelte

除了声明接收prop之外,还要修正路径拆分逻辑:SvelteKit的page.path永远以/开头,直接用索引0取值会拿到空字符串,索引1才是路径第一段的有效内容:

<script context="module">
    export const load = ({ page }) => {
        return {
            props: {
                currentSection: `${page.path}`.split('/')[1] || 'home',
                sections: ['home', 'dashboard', 'settings']
            }
        };
    }
</script>

<script>
    // 显式声明接收load返回的prop
    export let currentSection;
    export let sections;
</script>

<div class="min-h-screen bg-gray-100">
    <Header {currentSection} {sections} />
    <slot />
</div>

2. 修正Header.svelte

子组件同样需要显式声明接收父组件传递的prop,才能继续向下传递:

<script>
    import Menu from "$lib/nav/menu.svelte"
    export let currentSection;
    export let sections;
</script>

<Menu {currentSection} {sections}></Menu>

3. 修正Menu.svelte循环逻辑

你的sections是字符串数组,不是对象数组,循环时不需要做对象解构:

<script>
    export let sections;
    export let currentSection;
</script>

{#each sections as section}
    <a
        href="/{section}"
        class="{section == currentSection
            ? 'bg-gray-900 text-white'
            : 'text-gray-300 hover:bg-gray-700'} other-classes"
        >{section}</a
    >
{/each}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:39:03