gpt4 book ai didi

javascript - Svelte react 性如何在函数内部工作?

转载 作者:数据小太阳 更新时间:2023-10-29 05:34:28 24 4
gpt4 key购买 nike

我在 Svelte 的 react 性方面遇到了一些严重的问题。我已经隔离了我认为至少是我的主要问题之一。将变量绑定(bind)到复选框时,在函数内部而不是外部设置变量时, react 性似乎会中断。这是有意的行为吗?在那种情况下,为什么?预期的工作流程是什么?

示例代码,一个 Svelte 组件:

<script>
let foo = true;

// This assignment works both on the plain text view (Foo: true/false)
// and on the checkbox
// setInterval(() => foo = !foo, 500)

// This assignment works only on the plain text view (Foo: true/false)
// but not for the checkbox
function action() {
foo = !foo;
}
</script>

Foo: { foo }<br />
Checkbox: <input type="checkbox" bind:checked={ foo } on:click|preventDefault={ action } />

使用 Svelte REPL 查看这个问题:https://svelte.dev/repl/73de7d705ab3442786710cd88ea3f625?version=3.12.1

最佳答案

如果您将变量声明包装在没有任何时间限制的 setTimeout 中(使其默认为 0 并因此尽快运行),您的代码将有效。

function action() {
setTimeout(() => {
foo = !foo;
});
}

我希望我能解释为什么这有效,但我不能...

关于javascript - Svelte react 性如何在函数内部工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57970951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com