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 badges
Add a comment  | 

1 Answer 1

Reset to default 1

The 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