首页 > 解决方案 > Svelte {#await}..{:then} 阻止使用新数据复制 html

问题描述

我正在尝试使用 Sveltes{#await}..{:then}块来显示 NASA 当天的图像,但我得到了一个奇怪的间歇性结果。在第一页加载图像和数据加载就好了。当我使用页面上的日期选择器更改日期时,它应该用异步检索的所选日期的图像和描述替换当前图像和描述。但是,有时会发生的情况是,带有新数据的 html 刚刚被附加到页面底部,因此先前选择的日期的图像和描述仍然存在。

谁能告诉我如何确保删除以前的数据?或者这可能是某种竞争条件?

<script>
    import { fade } from 'svelte/transition';
    import Loader from '../components/Loader.svelte';
    import {getContext} from 'svelte';
    import { format, parseISO } from 'date-fns'

    let todaysDate =  format(new Date(), 'y-MM-dd');
    let selectedDate = todaysDate;

    async function getPhotoOfTheDay() {
        let data = "";
        if (selectedDate !== todaysDate) {
            let response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=` + selectedDate);
            data = await response.json();
        } else {
            console.log("use in memory data");
            data = getContext('dailyImage');
        }
        return data;
    }

    $: imageData = getPhotoOfTheDay(selectedDate);
    $: formattedDate = format(parseISO(selectedDate), 'MMMM d, y')
</script>

<svelte:head>
    <title>All About Space: Photo of the day</title>
</svelte:head>

<div id="content">
    <h1>Photo of the day on {formattedDate}</h1>
    <p class="instructions">Choose a day to see the photo of the day for that date:
        <input type="date" bind:value="{selectedDate}" max="{todaysDate}" >
    </p>

    {#if imageData===""}
        <p>error.. no data for the selected date</p>
    {:else}
        {#await imageData}
            <Loader show="true"/>
        {:then image}
            <div class="image-result" transition:fade="{{duration: 300}}">
                <h2>{image.title}</h2>
                <p>
                    <img src="{image.url}" alt="{image.title}" title="{image.title}"/>
                    {image.explanation}
                </p>
            </div>
        {:catch error}

        {error.message}

        {/await}

    {/if}
</div>

<style lang="stylus">
    #content {
        background: rgba(0,0,0,0.8);
        backdrop-filter: blur(6px);
        border-radius: 5px;
        width: 75%;
        margin: 0 auto;
        padding: 1rem 2rem;

        &:after {
            clear: both;
            content: "";
            display: block;
            width: 100%;
        }
    }

    .instructions {
        border-bottom: 1px solid gray;
        padding-bottom: 2rem;
    }

    input {
        padding: 0.5rem 1rem;
        font-size: 1rem;
        cursor: pointer;
        border: 0;
        border-radius: 3px;
    }

    img {
        float: left;
        padding: 0 1rem 1rem 0;
        max-width: 50%;
    }
</style>

标签: async-awaitsveltesappersvelte-3

解决方案


等待块中的转换存在一个活动错误。这似乎是你的问题:https ://github.com/sveltejs/svelte/issues/1591


推荐阅读