如何避免在 Svelte 中初始加载后显示加载状态?

How to avoid showing loading state after the initial load in Svelte?

在下面的示例中,当获取数据时,将显示“正在加载...”文本。

有没有办法避免在初始加载后显示此加载状态?

因此,当您单击“更新”按钮时,它不会显示“正在加载...”,而是将现有数据保留在 .loading class 中,并在加载新数据时进行更新它与新数据?

playground

<button on:click={() => namep = getName()}>Update</button>
{#await namep}
  <div>Waiting...</div>
{:then name}
  <div>Hello {name}!</div>
{/await}

<script>
  let i = 0
  function getName() {
    return new Promise((set) => setTimeout(() => set(`Alex ${i++}`), 1000))  
  }
  
  let namep = getName()
</script>

<style>
  .loading { color: #ccc; }
</style>

您可以通过在单独的变量中设置每个调用并在 #await 块的第一部分检查该变量并显示旧数据(如果存在)而不是加载消息来伪造它。这是一个REPL

<button on:click={() => namep = getName()}>Update</button>
{#await namep}
    {#if oldData}
        <div class="loading">Hello {oldData}!</div>
    {:else}
        <div class="loading">Waiting...</div>
    {/if}
{:then name}
  <div>Hello {name}!</div>
{/await}

<script>
  let i = 0
  let oldData
    
  function getName() {
    return new Promise((set) => setTimeout(() => set(`Alex ${i++}`), 1000)).then(a => {
            return oldData = a
        })
    }
  
  let namep = getName()
</script>

<style>
  .loading { color: #ccc; }
</style>

一个简单的解决方案是只使用将在 getName 函数的 Promise 中更新的反应变量 lastData。然后在您的模板中检查 lastData 是否定义为显示名称。您需要在 onMount 回调中进行第一个 getName 调用:

<button on:click={getName}>Update</button>
{#if lastData}
    <div>Hello {lastData}!</div>
{:else}
    <div>Waiting...</div>
{/if}

<script>
    import { onMount } from 'svelte'

    let i = 0
    let lastData = undefined

    function getName() {
        new Promise(() => {
            setTimeout(() => {
                lastData = `Alex ${i++}`
            }, 1000)
        })  
    }

    onMount(async () => {
        getName()
    })
</script>

<style>
    .loading { color: #ccc; }
</style>

参见REPL