【问题标题】:Svelte Store: Am I missing the point of the stores subscribe method?Svelte Store:我错过了商店订阅方法的要点吗?
【发布时间】:2022-07-21 00:35:46
【问题描述】:

我正在学习 Svelte 并尝试构建一个简单的 SPA。到目前为止,对我来说没有任何意义的最重要的事情是商店的订阅方法。在svelte.dev 上的所有示例中,它仅用于链接到取消订阅方法,以在组件被卸载/销毁时。

最重要的是,当我创建我的商店时,我已经这样做了。

import { writable } from 'svelte/store'

const store = writable(0);

function Notify()
{
    store.subscribe(value => console.log(value));
}

function DoThing(newValues)
{
   store.update(oldValues => oldValues = newValues);
   Notify();
}

但在我的日志中,它仍然运行了两次。尽管我只是在我的store.update 通话之后才调用它。

非常感谢任何解释我可能会误解或做错的事情。

【问题讨论】:

    标签: svelte-component svelte-store


    【解决方案1】:

    .subscribe() 只需调用一次 - 然后它就处于活动状态。所以在你的情况下你不需要Notify()

    REPL

    <script>
        import { writable } from 'svelte/store'
    
        const store = writable(0);
    
        store.subscribe(value => console.log(value));
    
        function doThing(newValues) {
            store.update(oldValues => oldValues = newValues);
        }
    
    </script>
    
    <button on:click={() => doThing(Math.random())}>
        doThing
    </button>
    

    调用.subscribe()返回一个可用于取消订阅的函数

    const unsubscribe = count.subscribe(value => {
        console.log(value);
    }); // logs 'got a subscriber', then '1'
    
    unsubscribe(); // logs 'no more subscribers'
    

    【讨论】:

      猜你喜欢
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多