async-await - 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>
解决方案
等待块中的转换存在一个活动错误。这似乎是你的问题:https ://github.com/sveltejs/svelte/issues/1591
推荐阅读
- python - 公式单元格引用增量
- fullcalendar - Fullcalendar V5:dayHeaders 在 resourceTimeGridDay 视图中不可见
- javascript - 检查元素中的十进制字符代码
- java - 通过 apache.commons.io.FileUtils deleteDirectory 删除的文件去哪里了?
- python - 如果我们将 wkhtmltopdf 用于 pdfkit,我们如何在 aws 上部署 django 应用程序?
- python - pyTelegramBotAPI:机器人在 Heroku 上大约 1 小时后停止运行
- node.js - 在 nodejs 中访问 oData
- javascript - 我正在使用 window.fetch 下载文件,但在服务器上生成错误文件而不是在本地
- html - 模态弹出窗口未打开
- c# - sqlcmd 在 MSI 安装程序项目上不返回任何值,而它通常返回安装程序类之外的值