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

SvelteKit中load函数数据无法传入组件,无限加载问题求助

解决SvelteKit load函数数据无法传入组件的问题

核心问题出在+page.ts的load函数返回结构上:SvelteKit的load函数返回的对象会直接作为组件的data属性,不需要额外嵌套props层,你当前的写法导致组件中data.article不存在,始终为undefined。

1. 修正+page.ts的load函数

将返回的props嵌套结构去掉,直接返回数据字段:

export const load: PageLoad = async ({ fetch, params }) => {
  const res = await fetch(`${import.meta.env.VITE_API_URL}/api/articles/${params.id}`);
  if (res.ok) {
    const article = await res.json();
    console.log("Article loaded successfully:", article);
    // 直接返回数据,无需props包裹
    return {
      article
    };
  } else {
    console.error('Failed to fetch article:', res.status);
    return {
      status: res.status,
      error: new Error('Failed to load the article')
    };
  }
};

2. 组件代码优化(可选)

修正load函数后,原组件代码已能正常工作,也可以简化逻辑提升可读性:

<script lang="ts">
  export let data;

  // 可选:用可选链简化赋值
  $: article = data?.article;
  
  $: if (article) {
    console.log("Article received in component:", article);
  }
</script>

{#if article}
  <article>
    <h1>{article.title}</h1>
    <p>{article.description}</p>
  </article>
{:else}
  <p>Loading the article...</p>
{/if}

或者直接在模板中判断data?.article,省去中间变量:

<script lang="ts">
  export let data;
</script>

{#if data?.article}
  <article>
    <h1>{data.article.title}</h1>
    <p>{data.article.description}</p>
  </article>
{:else}
  <p>Loading the article...</p>
{/if}

3. 验证逻辑

修正后,load函数返回的article会直接挂载到组件的data对象上,组件能正确读取到数据,页面会自动从加载状态切换为显示文章内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:04:58