更新 Svelte 可写存储(writable store)时的变异,该存储是一个对象

huangapple go评论72阅读模式
英文:

Mutation when updating a Svelte writable store that is an object

问题

我有一个可写的存储对象:

import { writable } from "svelte/store";

const myStore = writable({ a: 1, b: 2 });

从redux而来,我想知道,我能改变它吗?:

myStore.update((prev) => {
  prev.a++;
  return prev;
});
英文:

I have a writable store that is an object:

import { writable } from "svelte/store";

const myStore = writable({ a: 1, b: 2 });

Coming from redux, I wonder, can I mutate it?:

myStore.update((prev) => {
  prev.a++;
  return prev;
});

答案1

得分: 2

你可以只是改变它。这是如果你无论如何使用 $-syntax 会发生的情况,例如:

<button on:click={() => $myStore.a++} />

那只会改变存储并通过 set 触发更改通知。

英文:

You can just mutate it. It is what happens if you use $-syntax anyway, e.g.

&lt;button on:click={() =&gt; $myStore.a++} /&gt;

That would just mutate the store and fire a change notification via set.

huangapple
  • 本文由 发表于 2023年4月7日 01:02:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定