SvelteKit:'filtered' 不是具有 'subscribe' 方法的商店

SvelteKit: 'filtered' is not a store with a 'subscribe' method

我正在尝试编写一个 Pokedex SvelteKit 应用程序(作为 James Q Quick 的教程)。当我保存我的 index.svelte 文件时 - 它在这个问题的标题中指出错误。

我的index.svelte代码如下:

<script>
    import Nav from '../components/nav.svelte'
    import {pokemon} from '../stores/pokestore'
    import PokemanCard from "../components/pokemanCard.svelte"

    let searchTerm = "";
    let filtered = [];

    $: { // Reacts to any data that changes ($: {what will happen when data changes})
        if (searchTerm !== pokemon.searchTerm) {
            searchTerm = pokemon.searchTerm;
            filtered = filtered(pokemon.pokemons, searchTerm);
        }
    }
</script>

<svelte:head>
    <title>Svelte Kit Pokedex</title>
</svelte:head>

<!-- All HTML Work -->
<h1 class="text-4xl text-center m-8 uppercase">SvelteKit Pokedex</h1>
<input type="text" class="w-full rounded-md text-lg p-4 border-2 border-gray-200" placeholder="Search Pokemon" bind:value={searchTerm}>


<style>
</style>


<div class="py-4 grid gap-4 md:grid-cols-2 grid-cols-1">
    {#each $filtered as pokeman}
    <PokemanCard pokeman={pokeman} />
    {/each}
</div>

我该如何解决这个问题?

谢谢:)

filtered 只是一个数组,而不是一个 svelte store(或公开 subsribe() 方法的实体)所以你不能使用 $ shorthand 来订阅它。只需将它作为一个数组进行迭代(没有 $)。

{#each filtered as pokeman}
  ...
{/each}

但是 pokemon 是商店吗?如果是这样,您需要在反应语句中订阅它才能看到更改。

<script>
    import Nav from '../components/nav.svelte'
    import {pokemon} from '../stores/pokestore'
    import PokemanCard from "../components/pokemanCard.svelte"

    let searchTerm = "";
    let filtered = [];

    $: if (searchTerm !== $pokemon.searchTerm) {
         searchTerm = $pokemon.searchTerm;
         filtered = filtered($pokemon.pokemons, searchTerm); 
         // *Note: I'm not sure where this 'filtered()' method is coming from but it will conflict with your `filtered` array variable.
       }
 
</script>

<svelte:head>
    <title>Svelte Kit Pokedex</title>
</svelte:head>

<!-- All HTML Work -->
<h1 class="text-4xl text-center m-8 uppercase">SvelteKit Pokedex</h1>
<input type="text" class="w-full rounded-md text-lg p-4 border-2 border-gray-200" placeholder="Search Pokemon" bind:value={searchTerm}>


<style>
</style>


<div class="py-4 grid gap-4 md:grid-cols-2 grid-cols-1">
    {#each filtered as pokeman}
    <PokemanCard pokeman={pokeman} />
    {/each}
</div>

或者,您可以为 filtered collection 使用 svelte derived store,在这种情况下,您 使用 $ shorthand 迭代它

<script>
    import { derived } from 'svelte/store';
    import { pokemon } from './stores.js';

    const filtered = derived(
        pokemon,
        $pokemon => $pokemon.pokemons.filter(p => /* your filter logic */ )
    );
</script>

<div class="py-4 grid gap-4 md:grid-cols-2 grid-cols-1">
    {#each $filtered as pokeman}
    <PokemanCard pokeman={pokeman} />
    {/each}
</div>