Skip to content
Myr

map-set.md

This file

Path

website/i18n/zh-CN/docusaurus-plugin-content-docs/current/map-set.md

60 lines · 1.9 KiB · Markdown

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 07f5cc9 point at it.

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 1–60why, one step back
1---
2id: map-set3title: Map 和 Set4---56<center>7<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>8</center>910_⚠ 从版本6开始,对 `Map` 和 `Set` 的支持必须在启动应用程序时通过显式调用 [`enableMapSet()`](./installation.mdx#pick-your-immer-version)来开启_1112普通对象、数组、`Map` 和 `Set` 总是可以用 Immer 更新。一个使用 `Map` 和 Immer 的示例:1314```javascript15test("Producers can update Maps", () => {16 const usersById_v1 = new Map()1718 const usersById_v2 = produce(usersById_v1, draft => {19 // 修改 map 会生成一个新的 map20 draft.set("michel", {name: "Michel Weststrate", country: "NL"})21 })2223 const usersById_v3 = produce(usersById_v2, draft => {24 // 在 map 深处进行修改,同样会生成一个新的 map!25 draft.get("michel").country = "UK"26 })2728 // 我们每次都会得到一个新的 map29 expect(usersById_v2).not.toBe(usersById_v1)30 expect(usersById_v3).not.toBe(usersById_v2)31 // 显然它们的内容不同32 expect(usersById_v1).toMatchInlineSnapshot(`Map {}`)33 expect(usersById_v2).toMatchInlineSnapshot(`34 Map {35 "michel" => Object {36 "country": "NL",37 "name": "Michel Weststrate",38 },39 }40 `)41 expect(usersById_v3).toMatchInlineSnapshot(`42 Map {43 "michel" => Object {44 "country": "UK",45 "name": "Michel Weststrate",46 },47 }48 `)49 // 旧的从来不会被更改50 expect(usersById_v1.size).toBe(0)51 // 试图在 produce 之外修改 map 对象是不行的!52 expect(() => usersById_v3.clear()).toThrowErrorMatchingInlineSnapshot(53 `"This object has been frozen and should not be mutated"`54 )55})56```5758Immer 生成的 Map 和 Set 将被人为地设置为不可变。这意味着在 `produce` 之外尝试 `set`、`clear`等可变方法时,它们将抛出异常。5960注意:map 的**键**永远不会被更改!这样做是为了避免混淆语义并保持键始终引用相等