svelte - 如何在 svelte-sapper 中获取 location.state
问题描述
我有一个路由宠物/id,我正在尝试获取 id 并使用它获取我的 API 以获取单个宠物的信息。我怎样才能做到这一点?
我在 Sapper 文档中看到了 preload 函数,但显然这不是实现目标的正确方法,因为当我尝试打印我的宠物对象的属性时,我得到了未定义。
<script context="module">
export async function preload(page, session) {
const { id } = page.params;
const res = await
this.fetch(`http://localhost/api/public/api/pets/${id}`);
const pet = await res.json();
return { pet };
}
<svelte:head>
<title>{pet.name}</title>
</svelte:head>
<h1>{pet.name}</h1> // Undefined
解决方案
我发现了问题。由于该功能是异步的,因此需要一些时间才能完成,但我试图立即打印宠物名称。我所做的修复它是:
{#if pet} // Proceed to print the name when there is a pet
<h1>{pet[0].name}</h1>
{:else}
<h4>Loading...</h4> // Show a loading message while the function is executing
{/if}
推荐阅读
- javascript - 带有时间戳的对象数组的日期过滤[图表添加]
- snakemake - 用于输出文件命名的 Snakefile 和通配符/正则表达式
- python - scikit-learn 在 make_scorer 中苦苦挣扎
- javascript - 终止 JavaScript 中的处理程序执行
- android - Android Studio 错误:程序类型已存在:org.objectweb.asm.Edge
- java - 用于文本文件处理的 Java 多线程
- r - R中时间序列缺失数据的插补模型
- python - 从单词搜索游戏中找到解决方案
- java - AWS Api Gateway 缓存的响应
- javascript - 菜单中的链接不可点击