没有变化的苗条更新总是触发重新渲染

svelte update with no change always triggers re-render

我一直在玩 svelte,但我很难管理渲染。

我注意到每当调用商店的 update 方法时都会触发重新呈现,即使商店没有更改。我想我可能做错了什么,但我不确定它是什么。

这是一个简单的例子。我原以为单击按钮不会在控制台中显示任何内容,因为没有实际更改(例如 Redux),但我每次都会收到一条新消息。

App.svelte:

{#each $store as value}
    {value}
{/each}
<button on:click={updateStore} type="button">Click me</button>

<script>
    import { afterUpdate } from 'svelte'
    import { store, updateStore } from './store.js'
    
    afterUpdate(() => console.log('render'))
</script>

store.js:

import { writable } from 'svelte/store'

export const store = writable([])

export const updateStore = () => store.update(s => s)

有问题吗?我应该在我的控制台中显示这些消息,还是应该添加类似 get(store) 的内容来决定我是否要实际调用 update

Svelte 生成的代码对商店的价值一无所知,无论它是否更改,它都会在每次商店更新时呈现。为了实现你想要的,你必须用你自己的实现包装 writable 来检查对象引用是否改变并依赖于它是否发出事件。粗略实施:

export function customWritable (value, start) {
   const _writable = writable(value, start);
   const set = (newVal) => {
     if (newVal !== value) {
       value = newVal;
       _writable.set(newVal);
     }
   };
   const update = (updateFn) => {
      set(updateFn(value));
   };
   
   return { set, update, subscribe: _writable.subscribe };
}