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

标签 javascript svelte

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

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/

相关文章:

javascript - 使用 Date().getTime() 生成日期时,JavaScript 中出现 "invalid date"

javascript - fadeIn 使用 $(document).ready( ) 导致明显的滞后

javascript - API 调用失败时在浏览器控制台中显示错误是否不好?

javascript - 是否可以将 react 组件列表保存在状态中并渲染它们?

javascript - 使用 jQuery 在 SELECT 中选择一个 OPTION 在 Firefox 中不起作用

javascript - Android 上的 MonkeyTalk 和 WebChromeClient/onJsScript 冲突

rollupjs - 导入 svelte 组件省略 .svelte 扩展名

typescript - 有没有办法基于 Svelte 和 Typescript 创建一个 NeutralinoJS 项目?

javascript - 在 Svelte 组件中动态加载模板

javascript - 如何在 Svelte 中正确地动态添加和删除文本输入字段?