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 badges
Add a comment  | 

2 Answers 2

Reset to default 1

It 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