Javascript 苗条如何处理进口产品内的反应性

Javascript 苗条如何处理进口产品内的反应性,javascript,svelte,Javascript,Svelte,我有一个被导入函数改变的对象 我想知道如何使我的更改反映在测试变量中 // 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 th

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

我想知道如何使我的更改反映在测试变量中

// 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}
//app.svelte
从“/Simulations.js”导入{testFunction};
设a=[{b:1},{b:2}];
$:测试=a;
设置超时(()=>{
//此函数用于更改
//但不反映测试中的变化
测试功能(a);
//下面注释的代码有效
//a[0].b=55;
console.log(“值更改为dasda”)
},1000);
{#每个测试作为t}
这是一个测试值:{t.b}
{/每个} //simulation.js 函数testFunction(变量){ //此代码尽职尽责地更改对象的值 //然而,这一变化似乎没有得到重视 //通过反应变量 变量[0]。b=55; } 导出{testFunction}
正如(顺便说一句,这是一个很好的解读)中所述,Svelte只对当前组件中的分配做出反应。在其他文件中对变量进行变异时,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}
这很管用,但感觉有点不雅

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