gpt4 book ai didi

javascript - svelte 如何处理导入内部的 react 性

转载 作者:行者123 更新时间:2023-12-02 22:55:47 26 4
gpt4 key购买 nike

我有一个被导入函数更改的对象。

https://svelte.dev/repl/e934087af1dc4a25a1ee52cf3fd3bbea?version=3.12.1

我想知道如何使我的更改反射(reflect)在我的测试变量中

// app.svelte
<script>
import {testFunction} from "./Simulations.js";

let a = [{"b":1}, {"b":2}];
$:test = a;

setTimeout(() => {
// this function changes the value of a
// while not reflecting the changes in test
testFunction(a);
// the code commented below works
//a[0].b = 55;
console.log("Value changed asdasda")
},1000);

</script>

{#each test as t}
This is a test value: {t.b} <br/>
{/each}


// simulation.js
function testFunction(variable){
// this code changes the value of the object dutifully
// it seems however that the change is not picked up
// by the reactive variable
variable[0].b = 55;
}

export {testFunction}

最佳答案

Svelte Tutorial 中所述(顺便说一下,这是一本很好的书),Svelte 仅对当前组件中的分配使用react。当改变其他文件中的变量时,Svelte 无法识别该变量。

一种可能的解决方案是从 testFunction 返回变异数组并分配它:

// app.svelte
setTimeout(() => {
a = testFunction(a);
},1000);

// simulation.js
function testFunction(variable){
variable[0].b = 55;
return variable;
}

如果您这样做,则根本不需要 test 变量:

<script>
import {testFunction} from "./Simulations.js";

let a = [{"b":1}, {"b":2}];

setTimeout(() => {
a = testFunction(a);
},1000);
</script>

{#each a as val}
This is a test value: {val.b} <br/>
{/each}
<小时/>

编辑:我还应该提到,最简单的修复(如果 testFunction 来自外部源,也许更容易)就是重新分配 a 调用 testFunction 之后:

setTimeout(() => {
testFunction(a);
a = a
},1000);

这可行,但感觉有点不优雅。

关于javascript - svelte 如何处理导入内部的 react 性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57983689/

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