【问题标题】:Why doesn't the modification of a property via an object method trigger a re-render?为什么通过对象方法修改属性不会触发重新渲染?
【发布时间】:2022-01-01 06:48:04
【问题描述】:

在此示例中,对象上的方法和函数似乎都以相同的方式修改对象的属性,都使用赋值。但只有函数调用会触发重新渲染。为什么会这样,有没有办法修改该方法,以便它也触发重新渲染? (不将物业转换为商店)

->REPL

<script>    
    class N {
        constructor() {
            this.numbers = [1,2,3]
        }   
        add(newN) {
            this.numbers = [...this.numbers, newN]
            console.log('numbers >', this.numbers)
        }
    }
    
    const numObj = new N()
    
    function add(newN) {
        numObj.numbers = [...numObj.numbers, newN]
        console.log('numbers >', numObj.numbers)
    }
    
</script>

{#each numObj.numbers as n}
 {n}
{/each}
<br><br>

<button on:click={_=> numObj.add(4)}>
    add number
</button>
via 'object method'<br>

<button on:click={_=> add(4)}>
    add number
</button>
via 'component function'<br>

【问题讨论】:

    标签: svelte svelte-3


    【解决方案1】:

    区别在于对象上的add方法是对象的一个​​实现细节。对象内部的状态不受 Svelte 的控制。它不知道在对象上调用 add 会修改该对象的 numbers 属性——您在该方法内分配对象状态 (this.numbers),而不是 Svelte 组件状态。理论上,可以改进 Svelte 编译器来检测这一点,但它很快就会变得难以管理,尤其是当对象定义在组件之外时。

    但是,当您调用组件的 add 函数时,您将分配给 Svelte 组件状态 (numObj.numbers)。这使 Svelte 可以接手任务并触发反应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      • 2022-01-25
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多