为什么这个对象没有更新?

问题描述 投票:0回答:1

复制:https://svelte.dev/playground/4424d522f50847f0b872a094b7b2198b?version=5.18.0

我不明白为什么会出现这个错误:

[svelte] binding_property_non_reactive
`bind:value={content.one}` (Form.svelte:5:19) is binding to a non-reactive property
https://svelte.dev/e/binding_property_non_reactive

代码:

应用程序.svelte:

<script>
    import Form from "./Form.svelte";

    let changed = $state(false);
    
    let content = $derived({one: `hello ${changed}`, two: changed });
</script>

<Form bind:content={() => content, (v) => content = v} />

Form.svelte:

<script>
    let { content = $bindable() } = $props();
</script>

<input type="text" bind:value={content.one} />
svelte svelte-5
1个回答
-1
投票

您无法绑定到派生状态,如果您希望

content
既可绑定又对
change
做出反应,那么您可以使用
$state
符文声明它,并在
$effect
更新时使用
change
来更新它像这样:

<script>
    import Form from "./Form.svelte";

    let changed = $state(false);
    let content = $state({one: `hello ${changed}`, two: changed });
    $effect(() => {
        content = {one: `hello ${changed}`, two: changed }
    });
    
</script>

changed: {changed} <br>
content: {JSON.stringify(content)} <br> <br>

<!-- This does not work! -->
<!-- <Form bind:content /> -->

<Form bind:content={() => content, (v) => content = v} />

<br><br>

<button type="button" onclick={() => changed = !changed}>
    change from App
</button>

这会给你一个警告,

State referenced in its own scope will never update
但它应该仍然有效,如果你想摆脱警告然后使用这样的闭包声明内容:

let content = $state({one: `hello ${(() => {return changed})()}`, two: () => {return changed} });
© www.soinside.com 2019 - 2024. All rights reserved.