如何使用 svelte 获取远程 API?

How to fetch an remote API with svelte?

我正在从一个 API 中获取引述并且获取似乎有效,因为第一个 console.log 被正确调用,但第二个不是。内容是来自 API.

json 对象中的一个字段
<script>
    import { onMount } from "svelte";
    let non = [];


    onMount(async function() {
        const res = await fetch("https://api.quotable.io/random");
        const json = await res.json();
        non.push(json);
        console.log(non);
    });

</script>

<div>
   {#each non as {content}}
   <p>{content}{console.log(content)}</p>
   {/each}
</div>

Because Svelte's reactivity is triggered by assignments, using array methods like push and splice won't automatically cause updates.

在您的示例中,如果您将 non.push(json) 替换为 non = [json],它似乎 work

https://svelte.dev/tutorial/updating-arrays-and-objects

Svelte's reactivity is triggered by assignments. (Source: docs)

因此,如果您想将更多引号放入 non,您必须使用 non = [...non, json];

<script>
    import { onMount } from "svelte";
    let non = [];
    let gettingQuote = false;

    onMount(() => {
        getRandomQuote();
    });

    async function getRandomQuote() {
        gettingQuote = true;
        const res = await fetch("https://api.quotable.io/random");
        const json = await res.json();
        non = [...non, json];
        gettingQuote = false;
    }
</script>

<div>
    {#each non as {author, content}}
        <p>{content} - {author}</p>
    {/each}
    <button on:click={getRandomQuote} disabled={gettingQuote}>Get Quote</button>
    {#if gettingQuote}
        <span>Getting Quote...</span>
    {/if}
</div>

这是一个有效的 example