如何在 svelte-sapper 中获得 location.state

How to get location.state in svelte-sapper

我有一条路线 pet/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}