Svelte中传递嵌套可写Store作为Prop时的迭代报错问题
解决嵌套Svelte Store遍历时报错“collection is not a store with a subscribe method”
问题场景
尝试遍历一个嵌套了writable store的可写对象store时,触发错误:collection is not a store with a subscribe method 或 Uncaught TypeError: store.subscribe is not a function。
错误原因
在NestedCollection.svelte中,错误地将普通对象collection当作store使用了$前缀($collection)。collection是从$nestedStore中取出的普通对象,并非store,因此Svelte尝试订阅它时会抛出错误。真正的store是collection.children,需要正确引用这个嵌套store来获取其值。
解决方案
将collection.children赋值给局部变量,通过该变量使用$前缀获取store的值,确保Svelte正确订阅嵌套store并实现响应式更新。
修正后的代码
store.js(无需修改)
import {writable} from "svelte/store"; export const nestedStore = writable({ 123456: { title: "First Item in Collection (no children)", children: writable({}) }, 234567: { title: "Second Item in Collection (2 children)", children: writable({ 7890: { title: "Second Item Child 1" }, 7891: { title: "Second Item Child 2" } }) }, 345678: { title: "Third Item in Collection", children: writable({}) } });
App.svelte(优化绑定逻辑)
<script> import { nestedStore } from "./store"; import NestedCollection from "./NestedCollection.svelte"; </script> {#each Object.entries($nestedStore) as [collectionId, collection] (collectionId)} <h1>{collectionId}</h1> <NestedCollection collection={collection} /> {/each}
NestedCollection.svelte(核心修正)
<script> export let collection; // 将嵌套的store赋值给局部变量,以便使用$前缀订阅 const childrenStore = collection.children; </script> <li>{collection.title}</li> {#if Object.keys($childrenStore).length} <ul> {#each Object.entries($childrenStore) as [childId, child] (childId)} <svelte:self collection={child} /> {/each} </ul> {/if}
内容的提问来源于stack exchange,提问作者berg
相关产品推荐
相关产品推荐

