admin管理员组文章数量:1405170
I'm trying to use SvelteMap: /docs/svelte/svelte-reactivity#SvelteMap
but for some reason it's not reactive.
I am exporting it from a .svelte file:
export const items = new SvelteMap<number, Item>();
Item
is an object.
Then inside a function I change the contents, like:
const item = items.get(num);
item.someProp = newValue;
The map is update, but reactivity doesn't work in components.
I also tried to re-assign the item in that function
const item = items.get(num);
item.someProp = newValue;
items.set(num, item);
still no go..
I'm trying to use SvelteMap: https://svelte.dev/docs/svelte/svelte-reactivity#SvelteMap
but for some reason it's not reactive.
I am exporting it from a .svelte file:
export const items = new SvelteMap<number, Item>();
Item
is an object.
Then inside a function I change the contents, like:
const item = items.get(num);
item.someProp = newValue;
The map is update, but reactivity doesn't work in components.
I also tried to re-assign the item in that function
const item = items.get(num);
item.someProp = newValue;
items.set(num, item);
still no go..
Share Improve this question asked Mar 8 at 19:50 AlexAlex 66.2k185 gold badges460 silver badges651 bronze badges1 Answer
Reset to default 1The map will not make its contents reactive, just its own properties and methods.
So the items you put into the map need to be stateful, e.g.
const item = $state({ value: 1 });
items.set(0, item);
Playground
(For plain objects and arrays, $state
creates a proxy wrapper around the object which will fire signals that trigger reactivity on change. Class instances with $state
properties would work as well.)
If you cannot make the item reactive (e.g. because it is from a separate library), you could wrap the instance in an object and assign a new wrapper after the modification to trigger the reactivity of the map.
const { current } = items.get(num);
current.someProp = newValue;
items.set(num, { current }); // constructs new object
Playground
本文标签: javascriptSvelteMap not reactiveStack Overflow
版权声明:本文标题:javascript - SvelteMap not reactive - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744886683a2630528.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论