我有一个包含搜索栏的导航栏,如果该路线当前不是搜索栏的路线,那么它可以正常工作。但是,我希望能够在路线内进行搜索,但该组件不会重新运行。
我目前正在与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}
答案 0 :(得分:1)
您可以将获取配方的代码从onMount
中移出,并将其设置为单独的反应块:
let unsubscribe;
let allIngredients;
let allRecipes;
let error;
$: allIngredients && getRecipes(allIngredients)
const getRecipes = (allIngredients) => {
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");
}
}
onMount(async () => {
unsubscribe = searchItems.subscribe((items) => {
allIngredients = items;
});
})
onDestroy(() => {
if (unsubscribe) {
unsubscribe();
}
});
当{em> allIngredients 更改时,行$: allIngredients && getRecipes(allIngredients)
将执行,如果错误,它将停止,否则它将运行getRecipes并获取配方,更新其他变量。