【发布时间】:2020-12-08 10:51:18
【问题描述】:
我有一个包含搜索栏的导航栏,如果该路线当前不是搜索栏的路线,它就可以正常工作。但是,我希望能够在路由内进行搜索,但组件不会重新运行。
我目前正在使用 onMount,但尝试过 beforeUpdate 和 afterUpdate。我也尝试将它作为函数放在脚本中,但它没有更新。
数据首先从搜索栏传递到存储,然后新路由从存储中获取数据。这可能并不理想,但我没有找到将它传递下去的方法,因为它位于导航栏中。
这是搜索栏的代码,我尝试使用replaceState: True,但这似乎没有任何作用。
async function sendSearchTerms(terms) {
await goto("recipe", { replaceState: true });
searchItems.set(terms);
}
这是它重定向到的路由中的代码。
let unsubscribe;
let allIngredients;
let allRecipes;
let error;
onMount(async () => {
unsubscribe = searchItems.subscribe((items) => {
allIngredients = items;
});
const ingredients = fixTextArray(allIngredients);
console.log(ingredients);
if (ingredients) {
try {
const res = await fetch("dev_data/recipes.json");
if (res.status == 200) {
allRecipes = await res.json();
} else {
error = res.status;
}
} catch (err) {
alert(err);
}
} else {
console.log("CRAP");
}
});
onDestroy(() => {
if (unsubscribe) {
unsubscribe();
}
});
正如我提到的,如果我从另一条路线搜索结果很好,所以我最初的想法是替换 onMount,因为它已经挂载了。但这并没有起到任何作用,所以我猜 Sapper 会在某个地方保持状态,而不是强制重新加载相同的路线。
也许标记中可能有这样做的东西,所以我也包括在内:
{#if error}
<h1>{error}</h1>
{:else}
{#if allRecipes}
<div class="cards">
{#each allRecipes as recipe}
<Card title={recipe.title} link="/{recipe.id}" />
{:else}Loading{/each}
</div>
{:else}No recipes{/if}
{/if}
【问题讨论】: