Svelte store的subscribe()为何在值未变更时触发?
Svelte Store订阅函数在值未变更时重复触发的原因
问题背景
我定义了一个Svelte的可写Store activeAccountIndexStore,代码如下:
export const activeAccountIndexStore: Writable<number | "native" | null> = writable(null);
它的初始值是null,在完成部分网络请求后,会被设置为具体数字或字符串'native'。
同时我封装了一个订阅方法,供其他组件调用:
export const onChangeActiveAccount = (activeAccountHandler: ActiveAccountHandler) => { activeAccountIndexStore.subscribe((newValue) => { log(`➡️➡️➡️➡️➡️ activeAccountIndexStore new value`, newValue); if (newValue !== null) { const activeAccount = getActiveAccount(); activeAccountHandler(activeAccount); } }); };
异常现象
实际运行中发现,即使Store的值没有发生变化,订阅的处理函数仍会被重复调用,日志输出如下:
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value null stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value null stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0 stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0 stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0 stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0 stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
MDN的Svelte文档说明:
A store is an object with a subscribe() method that allows interested parties to be notified whenever the store value changes.
按照文档描述,只有当Store的值发生变化时才会触发订阅通知,但现在的情况明显不符合预期。我原本预期的日志应该是:
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value null stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
疑问
为什么Svelte Store的subscribe()会在值未变更时重复触发?
内容的提问来源于stack exchange,提问作者mikemaccana
相关产品推荐
相关产品推荐

