Solidjs:在createStore中使用Map不会在更改时更新

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

Solidjs: Use a Map in createStore does not update on change

问题

我对solidjs还相对新手,也许我已经忽略了一些东西,但考虑到以下示例,我试图理解这里的问题:

```javascript
const [state, setState] = createStore({ items: new Map() }); // 例如:Map<number, string>

在一个组件中,假设我想使用存储的派生状态,如下所示:

export const Overview = () => {
    const count = () => state.items.size;

    return (<div>{count()}</div>);
};

如果我现在向地图中添加一个新条目,我本来希望计数属性会自动更新,因为我使用了依赖项。

我尝试过使用数组而不是地图的示例,这个示例可以正常工作,并且组件显示了正确和预期的值。

有人可以指导我到文档中的正确部分,或者解释为什么数组能工作而地图不行吗?


<details>
<summary>英文:</summary>

I&#39;m fairly new to solidjs and maybe I&#39;ve overlooked something but given the following example I try to understand the issue here:

const [state, setState] = createStore({ items: new Map() }); // e.g. Map<number, string>


In a component let&#39;s say I want to use a derived state of the store like so:

export const Overview = () => {
const count = () => state.items.size;

return (&lt;div&gt;{count()&lt;/div&gt;);

};

If I now add a new entry to the map I would have expected that the count property would be updated automatically since I use the dependency.


I&#39;ve tried this example with an array instead of the map and this is working just fine and the component displays the correct and expected value(s).

Can somebody point me maybe to the correct section in the documentation or explain why a Map is not working but an array does?



</details>


# 答案1
**得分**: 1

A signals notify its subscribers when its value change but you are not setting a new value but inserting new item to it hence the action is not perceived as update. You should set a new map and move the inserted values into the new map by cloning the old one.

<details>
<summary>英文:</summary>

A signals notify its subscribers when its value change but you are not setting a new value but inserting new item to it hence the action is not perceived as update. You should set a new map and move the inserted values into the new map by cloning the old one.

</details>



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

发表评论

匿名网友

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

确定