immer如何处理具有贴图和集的对象关键帧



immer docs声明"映射的键从来没有起草过!这样做是为了避免混淆语义,并保持键始终引用相等",但我很难理解这意味着什么。

我预计这意味着在草案Map/Set中使用draft对象作为键将自动取消引用该键,就像我调用了例如map.set(original(key) || key, value)一样。然而,事实似乎并非如此,我不明白这句话的意思。

下面是一些例子来说明我的意思。我期望所有这些日志使用true

const { enableMapSet, produce } = immer;
enableMapSet();
const collection = {
map: new Map(),
set: new Set(),
storedAsObject: {},
storedAsDraft: {},
};
collection.set.add(collection.storedAsObject);
collection.map.set(collection.storedAsObject, 'value');
const newCollection = produce(collection, (draft) => {
console.log(draft.set.has(draft.storedAsObject)); // false
console.log(draft.map.has(draft.storedAsObject)); // false
draft.set.add(draft.storedAsDraft);
draft.map.set(draft.storedAsDraft, 'value');
});
console.log(newCollection.set.has(newCollection.storedAsDraft)); // true
console.log(newCollection.map.has(newCollection.storedAsDraft)); // false
<script src="https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js"></script>

特别是,后两者的差异似乎是一个bug,但文档所讨论的特殊行为只调用了地图,所以我不确定。

这意味着,如果你抓住Map的键,它们是对象,你不会得到草稿(就像你抓住值一样(,而是原始对象。

所以你不应该改变地图中使用的键。(例如,像Array.from(draftMap.keys())[0].counter++这样的东西不会被Immer处理(

最新更新