Svelte {#await}...{:then}块用新数据复制html。

问题描述 投票:0回答:1

我想用斯维茨 {#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-await svelte sapper svelte-3
1个回答
3
投票

await块中的过渡有一个活跃的bug。这似乎是你的问题。https:/github.comsveltejssvelteissues1591。

© www.soinside.com 2019 - 2024. All rights reserved.