admin管理员组文章数量:1300011
Parent component:
<script>
import Child from "./Child.svelte"
import { onMount } from "svelte";
import apireq from "./api.js";
let items = $state.raw([]);
let splitItems = $derived(items.splice(0, 5));
onMount(() => {
apireq().then(v => items = v)
})
</script>
<h1>item count in parent {items.length}</h1>
<Child items={splitItems} />
Child component
<script>
let props = $props();
let { items} = props;
</script>
item count in child:
<div>{items.length}</div>
Child component does not update after the api request. Still shows 0 count. Parent does update.
I tried with both $state
and $state.raw
. But I don't want full reactivity because it's a large array, and reactivity on assign should be enough.
This used to be so simple in svelte 4, but in 5 nothing works as expected :(
Parent component:
<script>
import Child from "./Child.svelte"
import { onMount } from "svelte";
import apireq from "./api.js";
let items = $state.raw([]);
let splitItems = $derived(items.splice(0, 5));
onMount(() => {
apireq().then(v => items = v)
})
</script>
<h1>item count in parent {items.length}</h1>
<Child items={splitItems} />
Child component
<script>
let props = $props();
let { items} = props;
</script>
item count in child:
<div>{items.length}</div>
Child component does not update after the api request. Still shows 0 count. Parent does update.
I tried with both $state
and $state.raw
. But I don't want full reactivity because it's a large array, and reactivity on assign should be enough.
This used to be so simple in svelte 4, but in 5 nothing works as expected :(
Share Improve this question edited Feb 12 at 11:22 Kirstie Wilkinson 3041 gold badge2 silver badges11 bronze badges asked Feb 11 at 15:47 AlexAlex 68.1k185 gold badges459 silver badges650 bronze badges2 Answers
Reset to default 1It looks like the issue is with how $derived
works in Svelte 5. Since splitItems
is derived from items.splice(0, 5)
, it won't update reactively because splice
mutates the array instead of returning a new one. Try using slice
instead:
let splitItems = $derived(() => items.slice(0, 5));
This ensures splitItems
updates when items changes. Also, make sure you're passing a reactive store or using $state
correctly in the child. Let me know if this helps!
You need $derived
or just destructure $props()
directly:
let props = $props();
let { items } = $derived(props);
// or
let { items } = $props();
(Also, using splice
to remove items from $state
in $derived
violates purity. One should not modify state in $derived
.)
本文标签: javascriptSvelte child component props doesn39t update on parent state changeStack Overflow
版权声明:本文标题:javascript - Svelte child component props doesn't update on parent state change - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741651368a2390500.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论