【问题标题】:How to get location.state in svelte-sapper如何在 svelte-sapper 中获取 location.state
【发布时间】:2019-11-24 13:00:51
【问题描述】:

我有一个路线宠物/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

【问题讨论】:

    标签: svelte sapper


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 2019-11-04
      • 2020-06-06
      • 2020-02-19
      • 2020-09-22
      • 1970-01-01
      • 2020-09-03
      • 2021-07-14
      • 1970-01-01
      相关资源
      最近更新 更多