如何在svelte-sapper中获取位置状态



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

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

     <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

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

    {#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}

最新更新