首页 > 解决方案 > 如何在 svelte-sapper 中获取 location.state

问题描述

我有一个路由宠物/id,我正在尝试获取 id 并使用它获取我的 API 以获取单个宠物的信息。我怎样才能做到这一点?

我在 Sapper 文档中看到了 preload 函数,但显然这不是实现目标的正确方法,因为当我尝试打印我的宠物对象的属性时,我得到了未定义。

     <script context="module">
       export async function preload(page, session) {
         const { id } = page.params;

         const res = await 
         this.fetch(`http://localhost/api/public/api/pets/${id}`);
         const pet = await res.json();

         return { pet };
       }

    <svelte:head>
       <title>{pet.name}</title>
    </svelte:head>

    <h1>{pet.name}</h1> // Undefined

标签: sveltesapper

解决方案


我发现了问题。由于该功能是异步的,因此需要一些时间才能完成,但我试图立即打印宠物名称。我所做的修复它是:

    {#if pet} // Proceed to print the name when there is a pet
      <h1>{pet[0].name}</h1>
    {:else}
      <h4>Loading...</h4> // Show a loading message while the function is executing
    {/if}

推荐阅读