Skip to content
Myr

docs: add chinese translation (#902)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* config: add i18n * docs: add chinese translation * theming improvement for dropdown

authored by 儿时 · committed by GitHub · parent 607b994 · Browse files · 27 files+2053 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

27 files+2053 added−1 removed

  • other:+2053 added−1 removed

27 files+2053 added−1 removed

added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/api.md+52 added
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/async.mdx+71 added
1---2id: async3title: 异步 producers & createDraft / finishDraft4sidebar_label: 异步 produce / createDraft5---67<center>8 <div9 data-ea-publisher="immerjs"10 data-ea-type="image"11 className="horizontal bordered"12 ></div>13</center> <details>14 <summary className="egghead-summary">15 egghead.io 第11课: 创建<b>异步</b> producers(以及为什么不应该这样做)16 </summary>17 <br />18 <div>19 <iframe20 width="760"21 height="427"22 scrolling="no"23 src="https://egghead.io/lessons/react-write-asynchronous-producers-in-immer-and-why-you-shouldn-t/embed"24 ></iframe>25 </div>26 <a27 className="egghead-link"28 href="https://egghead.io/lessons/react-write-asynchronous-producers-in-immer-and-why-you-shouldn-t"29 >30 Hosted on egghead.io31 </a>32</details>3334允许从 recipe 返回 Promise 对象。或者,换句话说,使用 `async / await`。这对于长时间运行的进程非常有用,只有在 Promise 链解析后才生成新对象。请注意,如果 producer 是异步的,`produce` 本身(即使是柯里化形式)也会返回一个 promise。例子:3536```javascript37import produce from "immer"3839const user = {40 name: "michel",41 todos: []42}4344const loadedUser = await produce(user, async function(draft) {45 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()46})47```4849_警告:请注意,draft 不应从异步程序中“泄露”并存储在其他地方。异步过程完成后,draft 仍将被释放_5051## `createDraft` and `finishDraft`5253`createDraft` 和 `finishDraft` 是两个底层函数,它们对于在 immer 之上构建抽象的库非常有用。它避免了为了使用 draft 始终创建函数。相反,人们可以创建一个 draft,对其进行修改,并在未来的某个时间完成该 draft,在这种情况下,将产生下一个不可变状态。例如,我们可以将上面的示例重写为:545556```javascript57import {createDraft, finishDraft} from "immer"5859const user = {60 name: "michel",61 todos: []62}6364const draft = createDraft(user)65draft.todos = await (await window.fetch("http://host/" + draft.name)).json()66const loadedUser = finishDraft(draft)67```6869注意:`finishDraft` 以一个 `patchListener` 作为第二个参数,可以用来记录 patches,类似于 `produce`7071_警告:一般情况下,我们建议使用 `producer` 而不是 `createDraft / finishDraft` 组合,`produce` 在使用中不易出错,并且在代码中更清楚地区分了可变性和不变性的概念。_
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/built-with.md+24 added
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/complex-objects.md+74 added
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/current.md+62 added
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/curried-produce.mdx+79 added
1---2id: curried-produce3title: 柯里化 producers4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12</center> <details>13 <summary className="egghead-summary">14 egghead.io 第六课: 使用柯里化简化代码15 </summary>16 <br />17 <div>18 <iframe19 width="760"20 height="427"21 scrolling="no"22 src="https://egghead.io/lessons/javascript-simplify-immer-producer-functions-using-currying/embed"23 ></iframe>24 </div>25 <a26 className="egghead-link"27 href="https://egghead.io/lessons/javascript-simplify-immer-producer-functions-using-currying"28 >29 Hosted on egghead.io30 </a>31</details>3233将函数作为第一个参数传递给 `produce` 会创建一个函数,该函数尚未将 `produce` 应用于特定 state,而是创建一个函数,该函数将应用于将来传递给它的任何 state。这通常称为柯里化。举个例子:3435```javascript36import produce from "immer"3738function toggleTodo(state, id) {39 return produce(state, draft => {40 const todo = draft.find(todo => todo.id === id)41 todo.done = !todo.done42 })43}4445const baseState = [46 {47 id: "JavaScript",48 title: "Learn TypeScript",49 done: true50 },51 {52 id: "Immer",53 title: "Try Immer",54 done: false55 }56]5758const nextState = toggleTodo(baseState, "Immer")59```6061上面的 `toggleTodo` 模式非常典型;传递一个现有的 state 来 `produce`,修改 `draft`,然后返回结果。由于 `state` 除了将其传递给 `produce` 之外没有其他任何用途,因此可以通过使用 `produce` 的柯里化形式来简化上面的示例,其中您只传递 `produce` recipe 函数,并且 `produce` 将返回一个应用 recipe 到基础状态的新函数。这允许我们缩短上述 `toggleTodo` 定义。6263```javascript64import produce from "immer"6566// curried producer:67const toggleTodo = produce((draft, id) => {68 const todo = draft.find(todo => todo.id === id)69 todo.done = !todo.done70})7172const baseState = [73 /* as is */74]7576const nextState = toggleTodo(baseState, "Immer")77```7879请注意,`id` 参数现在已成为 recipe 函数的一部分!这种拥有 curried producers 的模式与 React 中的 `useState` Hook 非常巧妙地结合在一起,我们将在下一页看到。
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/example-setstate.mdx+241 added
1---2id: example-setstate3title: React & Immer4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12</center>13<details>14 <summary className="egghead-summary">15 egghead.io 第八课: 使用 Immer 和 useState,或者 useImmer。16 </summary>17 <br />18 <div>19 <iframe20 width="760"21 height="427"22 scrolling="no"23 src="https://egghead.io/lessons/react-immutable-update-state-inside-react-components-with-useimmer/embed"24 ></iframe>25 </div>26 <a27 className="egghead-link"28 href="https://egghead.io/lessons/react-immutable-update-state-inside-react-components-with-useimmer"29 >30 Hosted on egghead.io31 </a>32</details>3334## useState + Immer3536`useState` hook 假定存储在其中的任何 state 都被视为不可变的。使用 Immer 可以大大简化 React 组件状态的深度更新。下面的例子展示了如何使用 `produce` 和 `useState` ,可以在 [CodeSandbox](https://codesandbox.io/s/immer-usestate-ujkgg?file=/src/index.js) 试试。3738```javascript39import React, { useCallback, useState } from "react";40import produce from "immer";4142const TodoList = () => {43 const [todos, setTodos] = useState([44 {45 id: "React",46 title: "Learn React",47 done: true48 },49 {50 id: "Immer",51 title: "Try Immer",52 done: false53 }54 ]);5556 const handleToggle = useCallback((id) => {57 setTodos(58 produce((draft) => {59 const todo = draft.find((todo) => todo.id === id);60 todo.done = !todo.done;61 })62 );63 }, []);6465 const handleAdd = useCallback(() => {66 setTodos(67 produce((draft) => {68 draft.push({69 id: "todo_" + Math.random(),70 title: "A new todo",71 done: false72 });73 })74 );75 }, []);7677 return (<div>{*/ See CodeSandbox */}</div>)78}79```8081## useImmer8283由于所有 state 的更新都使用 `produce` 包装的更新模式,所以我们可以通过将更新模式包装在 [use-immer](https://www.npmjs.com/package/use-immer) 包中来简化上述操作8485```javascript86import React, { useCallback } from "react";87import { useImmer } from "use-immer";8889const TodoList = () => {90 const [todos, setTodos] = useImmer([91 {92 id: "React",93 title: "Learn React",94 done: true95 },96 {97 id: "Immer",98 title: "Try Immer",99 done: false100 }101 ]);102103 const handleToggle = useCallback((id) => {104 setTodos((draft) => {105 const todo = draft.find((todo) => todo.id === id);106 todo.done = !todo.done;107 });108 }, []);109110 const handleAdd = useCallback(() => {111 setTodos((draft) => {112 draft.push({113 id: "todo_" + Math.random(),114 title: "A new todo",115 done: false116 });117 });118 }, []);119120 // etc121```122123完整的 demo 请参阅 [CodeSandbox](https://codesandbox.io/s/use-immer-bvd5v?file=/src/index.js)124125## useReducer + Immer126127与 `useState` 类似,`useReducer` 也与 Immer 巧妙结合,如 [CodeSandbox](https://codesandbox.io/s/immer-usereducer-bqpzn?file=/src/index.js:0-1018) 所示:128129```javascript130import React, {useCallback, useReducer} from "react"131import produce from "immer"132133const TodoList = () => {134 const [todos, dispatch] = useReducer(135 produce((draft, action) => {136 switch (action.type) {137 case "toggle":138 const todo = draft.find(todo => todo.id === action.id)139 todo.done = !todo.done140 break141 case "add":142 draft.push({143 id: action.id,144 title: "A new todo",145 done: false146 })147 break148 default:149 break150 }151 }),152 [153 /* initial todos */154 ]155 )156157 const handleToggle = useCallback(id => {158 dispatch({159 type: "toggle",160 id161 })162 }, [])163164 const handleAdd = useCallback(() => {165 dispatch({166 type: "add",167 id: "todo_" + Math.random()168 })169 }, [])170171 // etc172}173```174175## useImmerReducer176177同上,可以通过 `use-immer` 包中的 `useImmerReducer` 简化 ([demo](https://codesandbox.io/s/useimmerreducer-sycpb?file=/src/index.js))178179```javascript180import React, { useCallback } from "react";181import { useImmerReducer } from "use-immer";182183const TodoList = () => {184 const [todos, dispatch] = useImmerReducer(185 (draft, action) => {186 switch (action.type) {187 case "toggle":188 const todo = draft.find((todo) => todo.id === action.id);189 todo.done = !todo.done;190 break;191 case "add":192 draft.push({193 id: action.id,194 title: "A new todo",195 done: false196 });197 break;198 default:199 break;200 }201 },202 [ /* initial todos */ ]203 );204205 //etc206207```208209210## Redux + Immer211212Redux + Immer 在 [Redux Toolkit](https://redux-toolkit.js.org/usage/immer-reducers) 的文档中被广泛介绍。对于没有 Redux Toolkit 的 Redux,可以应用与上面应用于 `useReducer` 相同的技巧:使用 `produce` 包装 reducer 函数,您可以安全地修改 draft!213214例子:215216```javascript217import produce from "immer"218219// 初始 state220const INITIAL_STATE = [221 /* 一系列 todos */222]223224const todosReducer = produce((draft, action) => {225 switch (action.type) {226 case "toggle":227 const todo = draft.find(todo => todo.id === action.id)228 todo.done = !todo.done229 break230 case "add":231 draft.push({232 id: action.id,233 title: "A new todo",234 done: false235 })236 break237 default:238 break239 }240})241```
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/faq.md+46 added
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/freezing.mdx+39 added
1---2id: freezing3title: 自动冻结4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12</center> <details>13 <summary className="egghead-summary">14 egghead.io 第7课: Immer 自动冻结数据15 </summary>16 <br />17 <div>18 <iframe19 width="760"20 height="427"21 scrolling="no"22 src="https://egghead.io/lessons/javascript-produces-immutable-data-and-avoid-unnecessary-creation-of-new-data-trees-with-immer/embed"23 ></iframe>24 </div>25 <a26 className="egghead-link"27 href="https://egghead.io/lessons/javascript-produces-immutable-data-and-avoid-unnecessary-creation-of-new-data-trees-with-immer"28 >29 Hosted on egghead.io30 </a>31</details>3233Immer 自动冻结所有使用 `produce` 修改的任何 state。这可以防止在 producer 之外意外修改 state。在大多数情况下,这是最佳实践,但你可以通过 `setAutoFreeze(true / false)` 显式打开或关闭此功能。3435Immer 永远不会冻结不可枚举、非自己或符号属性的(内容),除非它们的内容是可以被 `draft` 的。3637_⚠️ Immer 以递归方式冻结所有内容,对于将来不会更改的大型数据对象,这可能会矫枉过正,在这种情况下,使用 `freeze` 函数 浅层冻结数据会更有效。⚠️_3839_⚠️ 如果启用了自动冻结,recipe 函数并非完全没有副作用:任何最终出现在 produce 结果中的普通对象或数组都将被冻结,即使这些对象在 producer 开始之前没有被冻结!⚠️_
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/installation.mdx+82 added
1---2id: installation3title: 安装4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12</center>1314Immer 可以作为直接依赖项安装,并且可以在任何 ES5 环境中工作:1516- Yarn: `yarn add immer`17- NPM: `npm install immer`18- CDN: 暴露的全局变量是 `immer`19 - Unpkg: `<script src="https://unpkg.com/immer"></script>`20 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer"></script>`21 - ⚠️ 使用 CDN 时,最好检查浏览器中的 url 并查看它解析为哪个版本,这样当更新发布时,您的用户不会意外地获得更新的版本。因此,请改用如下网址:https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js。在 URL 中将 production.min 替换为 development 以进行开发构建。2223## 选择您的 Immer 版本2425_本节仅适用于版本 6 及更高版本_2627为确保 Immer 尽可能小,并非每个项目都需要的功能已选择加入,并且必须明确启用。这可确保在将您的应用程序捆绑用于生产时,未使用的功能不会占用任何空间。2829可以选择加入以下功能:3031| 功能 | 描述 | 调用方法 |32| --- | --- | --- |33| ES 5 支持 | 如果您的应用程序需要能够在较旧的 JavaScript 环境(例如 Internet Explorer 或 React Native)上运行,请启用此功能。 | `enableES5()` |34| [ES2015 Map and Set 支持](./complex-objects.md) | 要使 Immer 能够对原生 Map 和 Set 集合进行操作,请启用此功能 | `enableMapSet()` |35| [JSON 补丁 支持](./patches.mdx) | Immer 可以跟踪您对 draft 对象所做的所有更改。这对于使用 JSON 补丁时传达更改很有用 | `enablePatches()` |36| **All of the above** | 不确定您需要哪些功能?我们建议在新项目上默认启用上述所有功能。几个 KB 的过早优化可能不值得一开始的麻烦。此外,启用或禁用功能不会影响 Immer 本身的性能 | `enableAllPlugins()` |3738例如,如果您想在 `Map` 上使用 `produce` ,则需要在应用程序启动期间启用此功能一次:3940```typescript41// 在你的应用程序入口文件42import {enableMapSet} from "immer"4344enableMapSet()4546// ...然后47import produce from "immer"4849const usersById_v1 = new Map([50 ["michel", {name: "Michel Weststrate", country: "NL"}]51])5253const usersById_v2 = produce(usersById_v1, draft => {54 draft.get("michel").country = "UK"55})5657expect(usersById_v1.get("michel").country).toBe("NL")58expect(usersById_v2.get("michel").country).toBe("UK")59```6061Immer 以大约 3KB 的 gzip 压缩开始。每个启用的插件都会增加 < 1 KB。细分如下6263```64Import size report for immer:65┌───────────────────────┬───────────┬────────────┬───────────┐66│ (index) │ just this │ cumulative │ increment │67├───────────────────────┼───────────┼────────────┼───────────┤68│ import * from 'immer' │ 5662 │ 0 │ 0 │69│ produce │ 3100 │ 3100 │ 0 │70│ enableES5 │ 3761 │ 3770 │ 670 │71│ enableMapSet │ 3885 │ 4527 │ 757 │72│ enablePatches │ 3891 │ 5301 │ 774 │73│ enableAllPlugins │ 5297 │ 5348 │ 47 │74└───────────────────────┴───────────┴────────────┴───────────┘75(this report was generated by npmjs.com/package/import-size)76```7778## Immer 使用在旧的 JavaScript 环境?7980默认情况下,`produce` 尝试使用代理以获得最佳性能。但是,在较旧的 JavaScript 引擎上,代理不可用。例如,在 Android 上运行 Microsoft Internet Explorer 或 React Native(如果 React Native < v0.59 或在 React Native < v0.64 上使用 Hermes 引擎)时。在这种情况下,Immer 将回退到与 ES5 兼容的实现,其工作方式相同,但速度稍慢8182从版本 6 开始,必须通过调用 `enableES5()` 显式启用对回退实现的支持
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/introduction.md+103 added
1---2id: introduction3title: Immer 入门4sidebar_label: 入门5slug: /6---78<center>9<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>10</center>1112<img src="/immer/img/immer-logo.svg" height="200px" align="right"/>1314# Immer15162019 年 “年度突破”[React 开源奖](https://osawards.com/react/)和“最有影响的贡献”[JavaScript 开源奖](https://osawards.com/javascript/)的获得者1718- 介绍博客: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)19- Egghead.io 简短课程,涵盖 Immer 的基本知识: [Simplify creating immutable data trees with Immer (7 分钟)](https://egghead.io/lessons/redux-simplify-creating-immutable-data-trees-with-immer)20- Egghead.io 免费深入课程: [Immutable JavaScript Data Structures with Immer (58 分钟)](https://egghead.io/courses/immutable-javascript-data-structures-with-immer)2122---2324Immer(德语为:always)是一个小型包,可让您以更方便的方式使用不可变状态。2526### Immer 简化了不可变数据结构的处理2728Immer 可以在需要使用不可变数据结构的任何上下文中使用。例如与 React state、React 或 Redux reducers 或者 configuration management 结合使用。不可变的数据结构允许(高效)的变化检测:如果对对象的引用没有改变,那么对象本身也没有改变。此外,它使克隆对象相对便宜:数据树的未更改部分不需要复制,并且在内存中与相同状态的旧版本共享2930一般来说,这些好处可以通过确保您永远不会更改对象、数组或映射的任何属性来实现,而是始终创建一个更改后的副本。在实践中,这可能会导致代码编写起来非常麻烦,并且很容易意外违反这些约束。 Immer 将通过解决以下痛点来帮助您遵循不可变数据范式:31321. Immer 将检测到意外 mutations 并抛出错误。332. Immer 将不再需要创建对不可变对象进行深度更新时所需的典型样板代码:如果没有 Immer,则需要在每个级别手动制作对象副本。通常通过使用大量 `...` 展开操作。使用 Immer 时,会对 `draft` 对象进行更改,该对象会记录更改并负责创建必要的副本,而不会影响原始对象。343. 使用 Immer 时,您无需学习专用 API 或数据结构即可从范例中受益。使用 Immer,您将使用纯 JavaScript 数据结构,并使用众所周知的安全地可变 JavaScript API。3536### 一个简单的比较示例3738```javascript39const baseState = [40 {41 title: "Learn TypeScript",42 done: true43 },44 {45 title: "Try Immer",46 done: false47 }48]49```5051假设我们有上述基本状态,我们需要更新第二个 todo,并添加第三个。但是,我们不想改变原始的 baseState,我们也想避免深度克隆(以保留第一个 todo)5253#### 不使用 Immer5455如果没有 Immer,我们将不得不小心地浅拷贝每层受我们更改影响的 state 结构5657```javascript58const nextState = baseState.slice() // 浅拷贝数组59nextState[1] = {60 // 替换第一层元素61 ...nextState[1], // 浅拷贝第一层元素62 done: true // 期望的更新63}64// 因为 nextState 是新拷贝的, 所以使用 push 方法是安全的,65// 但是在未来的任意时间做相同的事情会违反不变性原则并且导致 bug!66nextState.push({title: "Tweet about it"})67```6869#### 使用 Immer7071使用 Immer,这个过程更加简单。我们可以利用 `produce` 函数,它将我们要更改的 state 作为第一个参数,对于第二个参数,我们传递一个名为 recipe 的函数,该函数传递一个 `draft` 参数,我们可以对其应用直接的 `mutations`。一旦 `recipe` 执行完成,这些 `mutations` 被记录并用于产生下一个状态。 `produce` 将负责所有必要的复制,并通过冻结数据来防止未来的意外修改。7273```javascript74import produce from "immer"7576const nextState = produce(baseState, draft => {77 draft[1].done = true78 draft.push({title: "Tweet about it"})79})80```8182正在寻找结合 React 的 Immer?跳到 [React + Immer](example-setstate) 页面8384### Immer 如何工作8586基本思想是,使用 Immer,您会将所有更改应用到临时 _draft_,它是 _currentState_ 的代理。一旦你完成了所有的 _mutations_,Immer 将根据对 _draft state_ 的 _mutations_ 生成 nextState。这意味着您可以通过简单地修改数据来与数据交互,同时保留不可变数据的所有好处。8788![immer-hd.png](/img/immer.png)8990使用 Immer 就像拥有一个私人助理。助手拿一封信(当前状态)并给您一份副本(草稿)以记录更改。完成后,助手将接受您的草稿并为您生成真正不变的最终字母(下一个状态)。9192前往 [下一章节](./produce.mdx) 以进一步深入了解 `produce`9394## 好处9596- 遵循不可变数据范式,同时使用普通的 JavaScript 对象、数组、Sets 和 Maps。无需学习新的 API 或 "mutations patterns"!97- 强类型,无基于字符串的路径选择器等98- 开箱即用的结构共享99- 开箱即用的对象冻结100- 深度更新轻而易举101- 样板代码减少。更少的噪音,更简洁的代码102- 对 JSON 补丁的一流支持103- 小:3KB gzip
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/map-set.md+60 added
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 的**键**永远不会被更改!这样做是为了避免混淆语义并保持键始终引用相等
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/original.md+36 added
1---2id: original3title: 从 draft 中提取原始 state4sidebar_label: Original5---67<center>8<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>9</center>1011Immer中暴露了一个命名对象 `original`,将从 `produce` 内部的代理实例获取原始对象(对于未代理值返回 `undefined`。12一个好的例子是:当在一个树状 state 中使用严格相等搜索结点的时候它很有用。1314```js15import {original, produce} from "immer"1617const baseState = {users: [{name: "Richie"}]}18const nextState = produce(baseState, draftState => {19 original(draftState.users) // is === baseState.users20})21```2223只是想知道一个值是否是代理实例?使用 `isDraft` 函数!请注意,不能在不是 draft 的对象上调用 `original`。242526```js27import {isDraft, produce} from "immer"2829const baseState = {users: [{name: "Bobby"}]}30const nextState = produce(baseState, draft => {31 isDraft(draft) // => true32 isDraft(draft.users) // => true33 isDraft(draft.users[0]) // => true34})35isDraft(nextState) // => false36```
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/patches.mdx+230 added
1---2id: patches3title: Patches4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12</center>13<details>14 <summary className="egghead-summary">15 egghead.io 第14课: 使用 produceWithPatches 捕获 Patches16 </summary>17 <br />18 <div>19 <iframe20 width="760"21 height="427"22 scrolling="no"23 src="https://egghead.io/lessons/react-capture-patches-to-distribute-changes-in-app-state-with-immer-producewithpatches/embed"24 ></iframe>25 </div>26 <a27 className="egghead-link"28 href="https://egghead.io/lessons/react-capture-patches-to-distribute-changes-in-app-state-with-immer-producewithpatches"29 >30 Hosted on egghead.io31 </a>32</details>33<details>34 <summary className="egghead-summary">35 egghead.io 第16课: 使用 applyPatches 应用 Patches36 </summary>37 <br />38 <div>39 <iframe40 width="760"41 height="427"42 scrolling="no"43 src="https://egghead.io/lessons/react-apply-patches-using-immer-applypatches-to-synchronize-state-across-clients/embed"44 ></iframe>45 </div>46 <a47 className="egghead-link"48 href="https://egghead.io/lessons/react-apply-patches-using-immer-applypatches-to-synchronize-state-across-clients"49 >50 Hosted on egghead.io51 </a>52</details>5354_⚠ 在版本6之后,必须在启动应用程序调用一次 [`enablePatches()`](./installation.mdx#pick-your-immer-version) 来启用对 Patches 的支持。_5556在 producer 运行期间,Immer 可以记录所有的补丁来回溯 reducer造成的更改 。这是一个非常强大的工具,如果您想暂时 fork 您的状态并回溯对原始状态的更改。5758Patches 在下面场景很有用:5960- 与其他方交换增量更新,例如通过61- 对于调试/跟踪,准确查看状态如何随时间变化62- 作为撤消/重做的基础或作为在稍微不同的状态树上回溯更改的方法。6364为了帮助回溯补丁,`applyPatches` 派上用场了。这是一个如何使用 Patches 来记录增量更新并(反向)应用它们的示例:6566```javascript67import produce, {applyPatches} from "immer"6869// 版本 670import {enablePatches} from "immer"71enablePatches()7273let state = {74 name: "Micheal",75 age: 3276}7778// 假设用户在向导中79// 他的更改 应该以最终是否为基本状态结束...8081his changes should end up in the base state ultimately or not...82let fork = state83// 用户在向导中所作的所有更改84let changes = []85// 与向导中所做的所有更改相反86let inverseChanges = []8788fork = produce(89 fork,90 draft => {91 draft.age = 3392 },93 // 产生的第三个参数是一个回调,patches 将从这里产生94 (patches, inversePatches) => {95 changes.push(...patches)96 inverseChanges.push(...inversePatches)97 }98)99100// 同时,我们的原始状态被替换,例如101// 从服务器收到了一些更改102state = produce(state, draft => {103 draft.name = "Michel"104})105106// 当向导完成(成功)后,我们可以将 fork 中的更改重播到新的状态!107state = applyPatches(state, changes)108109// state 现在包含来自两个代码路径的更改!110expect(state).toEqual({111 name: "Michel", // 服务器更改112 age: 33 // 向导更改113})114115// 最后,即使在完成向导之后,用户也可能会改变主意并撤消他的更改......116state = applyPatches(state, inverseChanges)117expect(state).toEqual({118 name: "Michel", // 没有还原119 age: 32 // 还原了120})121```122123生成的 patches 与 [RFC-6902 JSON patch standard](https://datatracker.ietf.org/doc/html/rfc6902/#section-4.1) 类似(但并不相同),除了 path 属性是一个数组,而不是一个字符串。这使得处理 patches 更加容易。如果你想规范化到官方格式,`patch.path = patch.path.join("/")`应该可以解决这个问题。无论如何,下面就是一堆 patches 和它们回溯的样子。124125```json126[127 {128 "op": "replace",129 "path": ["profile"],130 "value": {"name": "Veria", "age": 5}131 },132 {"op": "remove", "path": ["tags", 3]}133]134```135136```json137[138 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},139 {"op": "add", "path": ["tags", 3], "value": "kiddo"}140]141```142143⚠ 注意: Immer 生成的补丁集应该是正确的,也就是说,将它们应用于相同的基础对象应该会导致相同的最终状态。然而,Immer 不保证生成的补丁集是最优的,即可能的最小补丁集。它通常取决于被认为是“最佳”的用例,并且生成最佳补丁集在计算上可能非常昂贵。因此,在某些情况下,您可能想要对生成的补丁进行后处理,或者按照下面的说明压缩它们。144145### `produceWithPatches`146147<details>148 <summary className="egghead-summary">149 egghead.io 第19课: 使用回溯 patches 构建撤销功能150 </summary>151 <br />152 <div>153 <iframe154 width="760"155 height="427"156 scrolling="no"157 src="https://egghead.io/lessons/react-use-immer-inversepatches-to-build-undo-functionality/embed"158 ></iframe>159 </div>160 <a161 className="egghead-link"162 href="https://egghead.io/lessons/react-use-immer-inversepatches-to-build-undo-functionality"163 >164 Hosted on egghead.io165 </a>166</details>167<details>168 <summary className="egghead-summary">169 egghead.io 第20课: 使用 patches 构建重做功能170 </summary>171 <br />172 <div>173 <iframe174 width="760"175 height="427"176 scrolling="no"177 src="https://egghead.io/lessons/react-use-immer-patches-to-build-redo-functionality/embed"178 ></iframe>179 </div>180 <a181 className="egghead-link"182 href="https://egghead.io/lessons/react-use-immer-patches-to-build-redo-functionality"183 >184 Hosted on egghead.io185 </a>186</details>187188除了设置 patch 监听器之外,获取 patches 的更简单方法是使用 `produceWithPatches`,它与 `produce` 具有相同的签名,不过它189不止返回 next state,而是一个包含 `[nextState, patches, inversePatches]` 的元组,和 `produce` 一样,`produceWithPatches` 也支持柯里化。190191```javascript192import {produceWithPatches} from "immer"193194const [nextState, patches, inversePatches] = produceWithPatches(195 {196 age: 33197 },198 draft => {199 draft.age++200 }201)202```203204将返回:205206```javascript207;[208 {209 age: 34210 },211 [212 {213 op: "replace",214 path: ["age"],215 value: 34216 }217 ],218 [219 {220 op: "replace",221 path: ["age"],222 value: 33223 }224 ]225]226```227228有关更深入的研究,请参阅使用 [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)229230提示:使用此技巧可以 [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69)
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/performance.mdx+83 added
1---2id: performance3title: Immer 性能4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12</center> <details>13 <summary className="egghead-summary">14 egghead.io 第5课: 在 React 中利用 Immer 的结构共享15 </summary>16 <br />17 <div>18 <iframe19 width="760"20 height="427"21 scrolling="no"22 src="https://egghead.io/lessons/react-profile-react-rendering-and-optimize-with-memo-to-leverage-structural-sharing/embed"23 ></iframe>24 </div>25 <a26 className="egghead-link"27 href="https://egghead.io/lessons/react-profile-react-rendering-and-optimize-with-memo-to-leverage-structural-sharing"28 >29 Hosted on egghead.io30 </a>31</details> <details>32 <summary className="egghead-summary">33 egghead.io 第7课: 如果没有语义变化,Immer 会使用原先的数据34 </summary>35 <br />36 <div>37 <iframe38 width="760"39 height="427"40 scrolling="no"41 src="https://egghead.io/lessons/javascript-produces-immutable-data-and-avoid-unnecessary-creation-of-new-data-trees-with-immer/embed"42 ></iframe>43 </div>44 <a45 className="egghead-link"46 href="https://egghead.io/lessons/javascript-produces-immutable-data-and-avoid-unnecessary-creation-of-new-data-trees-with-immer"47 >48 Hosted on egghead.io49 </a>50</details>5152这是一个关于 Immer 性能的 [简单 benchmark](https://github.com/immerjs/immer/blob/master/__performance_tests__/todo.js) 。该测试需要 50,000 个待办事项并更新其中的 5,000 个。 _Freeze_ 表示状态树在生成后已被冻结。这是一种开发最佳实践,因为它可以防止开发人员意外修改状态树。5354上面的数字没有反映一些东西,但实际上,Immer 有时比手写的 reducer _快_ 得多。这样做的原因是,Immer 会检测“无操作”状态变化,如果实际上没有任何变化,则返回原始状态,这可以避免很多重新渲染。众所周知,只需应用 immer 即可解决关键性能问题。5556这些测试在 Node 10.16.3 上执行。使用 `yarn test:perf` 在本地重现它们。5758![performance.png](/img/performance.png)5960最重要的结论:6162- Immer with proxies 大约比手写 reducer 慢 2 到 3 倍(上面的测试用例是最坏的情况,请参阅 `yarn test:perf` 了解更多测试情况)。这在实践中可以忽略不计。63- Immer 的速度大致与 ImmutableJS 一样快。但是,_immutableJS + toJS_ 明确了后期往往需要付出的代价;将 immutableJS 对象转换回普通对象,以便将它们传递给组件或者进行序列化操作在网络中传输......(还有将从服务器接收到的数据转换为不可变 JS 的前期成本)64- 生成 patches 不会显著减慢 immer65- ES5 后备实现的速度大约是代理实现的两倍,在某些情况下更糟。6667## 性能提示6869### 预冻结数据7071当向 Immer producer 中的状态树添加大型数据集时(例如从 JSON 端点接收的数据),可以在首先添加的数据的根上调用 `freeze(json)` ,来_浅冻结_它。这将允许 Immer 更快地将新数据添加到树中,因为它将避免_递归_扫描和冻结新数据的需要。7273### 您可以随时选择退出7475immer 在任何地方都是可选的,因此手动编写性能非常苛刻的 reducers ,并将 immer 用于所有普通的的 reducers 是非常好的。即使在 producer 内部,您也可以通过使用 `original` 或 `current` 函数来选择退出 Immer 的某些部分逻辑,并对纯 JavaScript 对象执行一些操作。7677### 对于昂贵的搜索操作,从原始 state 读取,而不是 draft7879Immer 会将您在 draft 中读取的任何内容也递归地转换为 draft。如果您对涉及大量读取操作的 draft 进行昂贵的无副作用操作,例如在非常大的数组中使用 `find(Index)` 查找索引,您可以通过首先进行搜索,并且只在知道索引后调用 `produce` 来加快速度。这样可以阻止 Immer 将在 draft 中搜索到的所有内容都进行转换。或者,使用 `original(someDraft)` 对 draft 的原始值执行搜索,这归结为同样的事情。8081### 将 produce 拉到尽可能远的地方8283始终尝试将 produce “向上”拉动,例如 `for (let x of y) produce(base, d => d.push(x))` 比 `produce(base, d => { for (let x of y) ) d.push(x)})` 慢得多
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/pitfalls.md+90 added
1---2id: pitfalls3title: 陷阱4---56<center>7<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>8</center>910### 性能提示1112对于性能提示,阅读 [性能提示](./performance.mdx#performance-tips).1314### 不要重新分配 recipe 参数1516永远不要重新分配 `draft` 参数(例如:`draft = myCoolNewState`)。相反,要么修改 draft,要么返回新状态。请参阅[从 producers 返回数据](./return.mdx)。1718### Immer 只支持单向树1920Immer 假设您的状态是单向树。也就是说,任何对象都不应该在树中出现两次,也不应该有循环引用。从根到树的任何节点应该只有一条路径。2122### 永远不要从 producer 那里显式返回 `undefined`2324可以从 producers 返回值,但不能以这种方式返回 `undefined`,因为它与根本不更新 draft 没有区别!如果你想用 `undefined` 替换 draft,只需从 producer 那里返回 `nothing`。2526### 不要修改特殊对象2728Immer [不支持特殊对象](https://github.com/immerjs/immer/issues/504) 比如 window.location.2930### 类应该是可 draft 的或不可变的3132您将需要使自己的类能与 Immer 一起正常工作。有关该主题的文档,请查看有关使用[复杂对象](./complex-objects.md)的部分。3334### 只有有效的索引和长度可以在数组上改变3536对于数组,只能改变数值属性和 `length` 属性。自定义属性不会保留在数组上。3738### 只有来自 state 的数据会被 draft3940请注意,来自闭包而不是来自基本 state 的数据将永远不会被 draft,即使数据已成为新 darft 的一部分。4142```javascript43function onReceiveTodo(todo) {44 const nextTodos = produce(todos, draft => {45 draft.todos[todo.id] = todo46 // 注意,因为 todo 来自外部,而不是 draft,所以他不会被 draft,47 // 所以下面的修改会影响原来的 todo!48 draft.todos[todo.id].done = true4950 // 上面的代码相当于51 todo.done = true52 draft.todos[todo.id] = todo53 })54}55```5657### Immer patches 不一定是最优的5859Immer 生成的 patches 应该是正确的,也就是说,将它们应用于相同的基础对象应该会导致相同的最终状态。然而,Immer 不保证生成的 patches 是最优的,即可能的最小 patches60### 始终使用嵌套 producers 的结果6162支持嵌套调用 `produce` ,但请注意 `produce` 将_始终_产生新状态,因此即使将 draft 传递给嵌套 produce,内部 produce 所做的更改也不会在传递给它的 draft 中可见,只会反映在产生的输出中。换句话说,当使用嵌套 produce 时,您会得到 draft 的 draft,并且内部 produce 的结果应该合并回原始 draft(或返回)。例如,如果内部 produce 的输出没有被使用的话, `produce(state, draft => {produce(draft.user, userDraft => { userDraft.name += "!" })})` 将不会生效。使用嵌套 producers 的正确方法是:636465```javascript66produce(state, draft => {67 draft.user = produce(draft.user, userDraft => {68 userDraft.name += "!"69 })70})71```7273### Drafts 在引用上不相等7475Immer 中的 draft 对象包装在 `Proxy` 中,因此您不能使用 `==` 或 `===` 来测试原始对象与其 draft 之间的相等性(例如,当匹配数组中的特定元素时)。相反,您可以使用 `original` 助手:767778```javascript79const remove = produce((list, element) => {80 const index = list.indexOf(element) // 不会工作!81 const index = original(list).indexOf(element) // 用这个!82 if (index > -1) list.splice(index, 1)83})8485const values = [a, b, c]86remove(values, a)87```8889如果可以的话,建议在 `produce` 函数之外执行比较,或者使用 `.id` 之类的唯一标识符属性,以避免需要使用 `original`。90
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/produce.mdx+91 added
1---2id: produce3title: 使用 produce4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12</center>13<details>14 <summary className="egghead-summary">15 egghead.io 第 3 课:使用 produce 简化深度更新16 </summary>17 <br />18 <div>19 <iframe20 width="760"21 height="427"22 scrolling="no"23 src="https://egghead.io/lessons/javascript-simplify-deep-state-updates-using-immer-produce/embed"24 ></iframe>25 </div>26 <a27 className="egghead-link"28 href="https://egghead.io/lessons/javascript-simplify-deep-state-updates-using-immer-produce"29 >30 Hosted on egghead.io31 </a>32</details>3334Immer 包暴露了一个完成所有工作的默认函数。3536`produce(currentState, recipe: (draftState) => void): nextState`3738`produce` 需要一个 `baseState`,以及一个可用于对传入的 `draft` 进行所有所需更改的 `recipe`。关于 Immer 的有趣之处在于 baseState 将保持不变,但 nextState 将反映对 DraftState 所做的所有更改.3940在 `recipe` 中,所有标准的 JavaScript API 都可以在 `draft` 对象上使用,包括属性字段分配、删除操作和修改数组、Map 和 Set 操作,如 push、pop、splice、set、sort、remove 等。4142这些 `mutations` 中的任何一个都不必发生在初始对象上,但它可以修改 `draft` 深处的任何内容:`draft.todos[0].tags["urgent"].author.age = 56`4344请注意,`recipe` 函数通常不会返回任何内容。但是,如果您想用另一个对象完全替换 `draft`,则可以返回,有关更多详细信息,请参阅返回[新数据](return)。4546## 例子4748```javascript49import produce from "immer"5051const baseState = [52 {53 title: "Learn TypeScript",54 done: true55 },56 {57 title: "Try Immer",58 done: false59 }60]6162const nextState = produce(baseState, draftState => {63 draftState.push({title: "Tweet about it"})64 draftState[1].done = true65})66```6768```javascript69// 新的 item 仅仅被添加到了 next state70// base state 没有被修改71expect(baseState.length).toBe(2)72expect(nextState.length).toBe(3)7374// 同上75expect(baseState[1].done).toBe(false)76expect(nextState[1].done).toBe(true)7778// 未修改的数据结构共享79expect(nextState[0]).toBe(baseState[0])80// 改变的数据不是81expect(nextState[1]).not.toBe(baseState[1])82```8384### 术语8586- `(base)state`, 传递给 `produce` 的不可变状态87- `recipe`: `produce` 的第二个参数,它捕获了 base state 应该如何 `mutated`。88- `draft`: 任何 `recipe` 的第一个参数,它是可以安全 `mutate` 的原始状态的代理。89- `producer`. 一个使用 `produce` 的函数,通常形式为 `(baseState, ...arguments) => resultState`9091请注意,命名 `recipe` 的第一个参数 `draft` 并不是绝对必要的。您可以将其命名为任何您想要的名称,例如 `user`。使用 `draft` 作为名称只是一个约定,以表明:“这里的 `mutation` 是可以的”。
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/resources.md+18 added
1---2id: resources3title: 外部资源4---56<center>7<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>8</center>910- 博客: [Immer 在 React 中的兴起](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)11- 博客: 由 Workday Prism 解释他们为什么选择 Immer 来管理不可变状态 [寻找强类型、不可变的状态](https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5)12- 博客: [React 和 Redux 中的不可变性:完整指南](https://daveceddia.com/react-redux-immutability-guide/)13- 视频教程: [将 Immer 与 React.setState 一起使用](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)14- Michel Weststrate 在 React Finland 2018 上的 Immer [演讲](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [幻灯片](http://immer.surge.sh/)15- [ForwardJS 2019:不可变性正在改变——从 Immutable.js 到 Immer](https://www.youtube.com/watch?v=bFuRvcAEiHg&feature=youtu.be) by [shawn swyx wang](https://twitter.com/swyx/)16- [演讲:Immer、不可变性和代理的奇妙世界](https://www.youtube.com/watch?v=4Nb9Gwp2L24) + [幻灯片](https://jsnation-proxies.surge.sh/), JSNation 2019, Michel Weststrate17- 博客: [使用快照、patches 和操作分发状态更改](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-1-2811a2fcd65f)18- 博客: [在 Redux 中实现 Undo-Redo 功能](https://techinscribed.com/implementing-undo-redo-functionality-in-redux-using-immer/), 2019年9月
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/return.mdx+152 added
1---2id: return3title: 从 producers 返回新数据4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12</center>13<details>14 <summary className="egghead-summary">15 egghead.io 第9课: 返回全新 state16 </summary>17 <br />18 <div>19 <iframe20 width="760"21 height="427"22 scrolling="no"23 src="https://egghead.io/lessons/react-return-completely-new-state-from-an-immer-producer/embed"24 ></iframe>25 </div>26 <a27 className="egghead-link"28 href="https://egghead.io/lessons/react-return-completely-new-state-from-an-immer-producer"29 >30 Hosted on egghead.io31 </a>32</details>3334不需要从 producer 那里返回任何东西,因为 Immer 无论如何都会返回 `draft` 的(最终)版本。但是,也允许仅仅 `return draft`。3536也允许从 producer 函数中任意返回其他数据。但_前提_是你没有修改 `draft`。这对于产生一个全新的 state 很有用。一些例子:3738```javascript39const userReducer = produce((draft, action) => {40 switch (action.type) {41 case "renameUser":42 //可以: 我们修改了当前的 state43 draft.users[action.payload.id].name = action.payload.name44 return draft // 与仅仅 'return' 相同45 case "loadUsers":46 // 可以: 我们返回了一个全新的 state47 return action.payload48 case "adduser-1":49 // 不行: 这不会改变 draft ,也不会返回新的状态50 // 它不会修改 draft(它只是重新声明它)51 // 事实上,这根本没有做任何事情52 draft = {users: [...draft.users, action.payload]}53 return54 case "adduser-2":55 // 不行: 修改 draft 的同时返回了一个新的状态56 draft.userCount += 157 return {users: [...draft.users, action.payload]}58 case "adduser-3":59 // 可以: 返回一个新的状态。但是,不必要的复杂和昂贵60 return {61 userCount: draft.userCount + 1,62 users: [...draft.users, action.payload]63 }64 case "adduser-4":65 // 可以: immer 的方式66 draft.userCount += 167 draft.users.push(action.payload)68 return69 }70})71```7273_注意:无法以这种方式返回 `undefined` ,因为它与不更新 draft 没有区别!继续阅读......_7475## 使用 `nothing` 产生 `undefined` 7677因此,一般来说,可以通过从 producer 返回一个新值来替换当前 state,而不是修改 draft。然而,有一个微妙的边缘情况:如果您尝试编写一个想要用 undefined 替换当前状态的 producer:7879```javascript80produce({}, draft => {81 // 什么也不干82})83```8485或者:8687```javascript88produce({}, draft => {89 // 尝试从 producer 中返回 undefined90 return undefined91})92```9394问题在于,在 JavaScript 中,一个不返回任何内容的函数也会返回 `undefined`!所以 immer 无法区分这些不同的情况。因此,默认情况下,Immer 会假设任何返回 `undefined` 的 producer 只是试图修改 draft。9596但是,为了让 Immer 清楚您有意生成 `undefined` 值,您可以返回内置标记 `nothing`:9798```javascript99import produce, {nothing} from "immer"100101const state = {102 hello: "world"103}104105produce(state, draft => {})106produce(state, draft => undefined)107// 都会返回最初的状态: { hello: "world"} 108109produce(state, draft => nothing)110// 产生一个新的状态, 'undefined'111```112113注:请注意,此问题特定于 `undefined` 值,任何其他值(包括 `null`)都不会受到此问题的影响114115提示:为了能够在使用 TypeScript 时从 recipe 中返回 `nothing`,`state` 的类型必须接受 undefined 值。116117## 使用 `void` 的内联快捷方式118119<details>120 <summary className="egghead-summary">121 egghead.io 第10课: 使用 _void_ 避免意外的返回 122 </summary>123 <br />124 <div>125 <iframe126 width="760"127 height="427"128 scrolling="no"129 src="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword/embed"130 ></iframe>131 </div>132 <a133 className="egghead-link"134 href="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword"135 >136 Hosted on egghead.io137 </a>138</details>139140Immer 中的 draft 修改通常需要一段代码块,因为返回表示覆盖。有时候你可能觉得这么多的样板代码很糟心。141142在这种情况下,您可以使用 javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) 运算符,它计算表达式并返回 `undefined`。143144```javascript145// 单次修改146produce(draft => void (draft.user.age += 1))147148// 多次修改149produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))150```151152代码风格是高度个人化的,但对于要被许多人理解的代码库,我们建议坚持经典的 `draft => { draft.user.age += 1}` 以避免认知开销。
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/support.md+13 added
1---2id: support3title: 赞助 immer4---56<center>7<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>8</center>910Immer 目前在 GitHub 上有 350000 个项目依赖于它,每月的下载量接近 10000000 次。然而,只有一开始两天的开发得到了赞助(由 Mendix),之后的所有开发和维护都是用爱发电。1112如果您喜欢 Immer,并且对这个包心存感激,或者想确保它的使用寿命,请考虑在 https://opencollective.com/immer 上赞助或使用 [PayPal](https://www.paypal.me/michelweststrate) 进行一次性捐赠。13
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/typescript.mdx+210 added
1---2id: typescript3title: Using TypeScript or Flow4sidebar_label: TypeScript / Flow5---67<center>8 <div9 data-ea-publisher="immerjs"10 data-ea-type="image"11 className="horizontal bordered"12 ></div>13</center> <details>14 <summary className="egghead-summary">15 egghead.io 第12课: Immer + TypeScript16 </summary>17 <br />18 <div>19 <iframe20 width="760"21 height="427"22 scrolling="no"23 src="https://egghead.io/lessons/react-type-immutable-immer-data-with-typescript/embed"24 ></iframe>25 </div>26 <a27 className="egghead-link"28 href="https://egghead.io/lessons/react-type-immutable-immer-data-with-typescript"29 >30 Hosted on egghead.io31 </a>32</details>3334Immer 包附带了类型定义,TypeScript 和 Flow 开箱即可获取这些定义,无需进一步配置3536TypeScript 类型会自动从 draft 类型中删除 `readonly` 修饰符,并返回与原始类型匹配的值。看这个实际的例子:3738```ts39import produce from "immer"4041interface State {42 readonly x: number43}4445// `x` 不能被修改46const state: State = {47 x: 048}4950const newState = produce(state, draft => {51 // `x` 可以被修改52 draft.x++53})5455// `newState.x` 不能在这里被修改56```57这确保了您可以修改状态的唯一位置是在您的 produce 回调中。它甚至可以递归地和 `ReadonlyArray` 一起工作。5859## 最佳实践60611. 始终尽可能将您的 state 定义为只读。这最好地反映了心智模型和现实,因为 Immer 将冻结其所有返回值。622. 您可以使用实用类型 `Immutable` 递归地使整个类型树成为只读的,例如:`type ReadonlyState = Immutable<State>`633. 如果输入状态的原始类型不是不可变的,则 Immer 不会自动将所有返回的类型包装在 `Immutable` 中。这是为了确保它不会破坏不使用不可变类型的代码库。6465## 柯里化 producers 的提示6667我们尝试尽可能多地推断。因此,如果创建了一个柯里化 producer 并直接传递给另一个函数,我们可以从那里推断出类型。这适用于例如 React:68```typescript69import {Immutable, produce} from "immer"7071type Todo = Immutable<{72 title: string73 done: boolean74}>7576// 然后...7778const [todo, setTodo] = useState<Todo>({79 title: "test",80 done: true81})8283// 然后...8485setTodo(86 produce(draft => {87 // draft 将是强类型和可变的!88 draft.done = !draft.done89 })90)91```9293当柯里化 producers 没有直接传递到其他地方时,Immer 可以从 draft 参数推断状态类型。例如在执行以下操作时:9495```typescript96// 请参阅下文以获得更好的解决方案9798const toggler = produce((draft: Draft<Todo>) => {99 draft.done = !draft.done100})101102// typeof toggler = (state: Immutable<Todo>) => Writable<Todo>103```104105请注意,我们确实用 `Draft` 包装了 `draft` 参数的 `Todo` 类型,因为 `Todo` 是只读类型。对于非只读类型,这不是必需的106107对于返回的柯里化函数 `toggler`,我们将输入类型缩小为 `Immutable<Todo>`,这样即使 `Todo` 是可变类型,我们仍将接受不可变的 todo 作为切换器的输入参数。108109与之相反,Immer 会将柯里化函数的输出类型_扩展_为 `Writable<Todo>`,以确保它的输出状态也可分配给未明确键入为不可变的变量。110111这种类型的缩小/扩大行为可能不受欢迎,甚至可能因为它会导致类型非常多的噪音。因此,我们建议为柯里化 produces 指定 state 泛型 ,以防它无法直接推断,例如上面的 `toggler`。通过这样做,将跳过自动输出扩大/输入缩小。然而,`draft` 参数本身仍将被推断为可写 `Draft<Todo>`:112113114```typescript115const toggler = produce<Todo>(draft => {116 draft.done = !draft.done117})118119// typeof toggler = (state: Todo) => Todo120```121122但是,如果柯里化 producer 定义了初始状态,Immer 可以从初始状态推断状态类型,因此在这种情况下也不需要指定泛型:123124```typescript125const state0: Todo = {126 title: "test",127 done: false128}129130// 不需要类型注释,因为我们可以从 state0 推断。131const toggler = produce(draft => {132 draft.done = !draft.done133}, state0)134135// typeof toggler = (state: Todo) => Todo136```137138如果 toggler 没有初始状态,并且它有柯里化参数,并且您显式设置 state 泛型,则任何附加参数的类型也应显式定义为元组类型:139140```typescript141const toggler = produce<Todo, [boolean]>((draft, newState) => {142 draft.done = newState143})144145// typeof toggler = (state: Todo, newState: boolean) => Todo146```147148## 类型转换149150`produce` 内部和外部的类型在概念上可以相同,但从实际角度来看是不同的。例如,上面示例中的 `State` 应被视为在 `produce` 外部不可变,但在 `produce` 内部是可变的。151152有时这会导致实际冲突。举个例子:153154```typescript155type Todo = {readonly done: boolean}156157type State = {158 readonly finishedTodos: readonly Todo[]159 readonly unfinishedTodos: readonly Todo[]160}161162function markAllFinished(state: State) {163 produce(state, draft => {164 draft.finishedTodos = state.unfinishedTodos165 })166}167```168169这将产生错误:170171```172The type 'readonly Todo[]' is 'readonly' and cannot be assigned to the mutable type '{ done: boolean; }[]'173```174175这个错误的原因是我们将只读的、不可变的数组分配给我们的 draft,draft 需要一个可变的类型,并带有 .push 等方法。就 TS 而言,这些并没有从我们的原始 `State` 中暴露出来。为了提示 TypeScript 我们希望将此处的集合向上转换为可变数组以用于 draft,我们可以使用函数 `castDraft`:176177178`draft.finishedTodos = castDraft(state.unfinishedTodos)` 将使错误消失。179180还有函数 `castImmutable`,以防您需要实现相反的效果。请注意,这些函数出于所有实际目的都是无操作的,它们只会返回其原始值。181182提示:您可以将 `castImmutable` 与 `produce` 结合起来,将 `produce` 的返回类型定义为不可变的内容,即使原始 state 是可变的183184```typescript185// 一个可变数据结构186const baseState = {187 todos: [{188 done: false189 }]190}191192const nextState = castImmutable(produce(baseState, _draft => {}))193194// nextState 的推断类型现在是:195{196 readonly todos: ReadonlyArray<{197 readonly done: boolean198 }>199})200```201202## 兼容性203204**注意:** Immer v5.3+ 仅支持 TypeScript v3.7+205206**注意:** Immer v3.0+ 仅支持 TypeScript v3.4+207208**注意:** Immer v1.9+ 仅支持 TypeScript v3.1+209210**注意:** 在未来的版本中可能会删除 flow 支持,我们建议使用 TypeScript
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current/update-patterns.md+142 added
1---2id: update-patterns3title: 更新模式4---56<center>7<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>8</center>910在 Immer 之前,使用不可变数据意味着学习所有不可变的更新模式。1112为了帮助“忘记”这些模式,这里概述了如何利用内置 JavaScript API 来更新对象和集合1314### 更新对象1516```javascript17import produce from "immer"1819const todosObj = {20 id1: {done: false, body: "Take out the trash"},21 id2: {done: false, body: "Check Email"}22}2324// 添加25const addedTodosObj = produce(todosObj, draft => {26 draft["id3"] = {done: false, body: "Buy bananas"}27})2829// 删除30const deletedTodosObj = produce(todosObj, draft => {31 delete draft["id1"]32})3334// 更新35const updatedTodosObj = produce(todosObj, draft => {36 draft["id1"].done = true37})38```3940### 更新数组4142```javascript43import produce from "immer"4445const todosArray = [46 {id: "id1", done: false, body: "Take out the trash"},47 {id: "id2", done: false, body: "Check Email"}48]4950// 添加51const addedTodosArray = produce(todosArray, draft => {52 draft.push({id: "id3", done: false, body: "Buy bananas"})53})5455// 索引删除56const deletedTodosArray = produce(todosArray, draft => {57 draft.splice(3 /*索引 */, 1)58})5960// 索引更新61const updatedTodosArray = produce(todosArray, draft => {62 draft[3].done = true63})6465// 索引插入66const updatedTodosArray = produce(todosArray, draft => {67 draft.splice(3, 0, {id: "id3", done: false, body: "Buy bananas"})68})6970// 删除最后一个元素71const updatedTodosArray = produce(todosArray, draft => {72 draft.pop()73})7475// 删除第一个元素76const updatedTodosArray = produce(todosArray, draft => {77 draft.shift()78})7980// 数组开头添加元素81const addedTodosArray = produce(todosArray, draft => {82 draft.unshift({id: "id3", done: false, body: "Buy bananas"})83})8485// 根据 id 删除86const deletedTodosArray = produce(todosArray, draft => {87 const index = draft.findIndex(todo => todo.id === "id1")88 if (index !== -1) draft.splice(index, 1)89})9091// 根据 id 更新92const updatedTodosArray = produce(todosArray, draft => {93 const index = draft.findIndex(todo => todo.id === "id1")94 if (index !== -1) draft[index].done = true95})9697// 过滤98const updatedTodosArray = produce(todosArray, draft => {99 // 过滤器实际上会返回一个不可变的状态,但是如果过滤器不是处于对象的顶层,这个依然很有用100 return draft.filter(todo => todo.done)101})102```103104### 嵌套数据结构105106```javascript107import produce from "immer"108109// 复杂数据结构例子110const store = {111 users: new Map([112 [113 "17",114 {115 name: "Michel",116 todos: [117 {118 title: "Get coffee",119 done: false120 }121 ]122 }123 ]124 ])125}126127// 深度更新128const nextStore = produce(store, draft => {129 draft.users.get("17").todos[0].done = true130})131132// 过滤133const nextStore = produce(store, draft => {134 const user = draft.users.get("17")135136 user.todos = user.todos.filter(todo => todo.done)137})138```139140请注意,许多数组操作可用于通过传递多个参数或使用展开操作来一次插入多个元素:`todos.unshift(...items)`。141142请注意,当处理包含通常由某个 id 标识的对象的数组时,我们建议使用基于 `Map` 或索引的对象(如上所示)而不是执行频繁的查找操作,查找表通常执行效率更高。
added:website/i18n/zh-CN/docusaurus-plugin-content-docs/current.json+18 added
1{2 "version.label": {3 "message": "Next",4 "description": "The label for version current"5 },6 "sidebar.Immer.category.Basics": {7 "message": "基础",8 "description": "The label for category Basics in sidebar Immer"9 },10 "sidebar.Immer.category.Advanced Features": {11 "message": "高级",12 "description": "The label for category Advanced Features in sidebar Immer"13 },14 "sidebar.Immer.category.Resources": {15 "message": "资源",16 "description": "The label for category Resources in sidebar Immer"17 }18}
added:website/i18n/zh-CN/docusaurus-theme-classic/footer.json+6 added
1{2 "copyright": {3 "message": "Copyright © 2022 Michel Weststrate",4 "description": "The footer copyright"5 }6}
added:website/i18n/zh-CN/docusaurus-theme-classic/navbar.json+18 added
1{2 "title": {3 "message": "Immer",4 "description": "The title in the navbar"5 },6 "item.label.Documentation": {7 "message": "文档",8 "description": "Navbar item with label Documentation"9 },10 "item.label.GitHub": {11 "message": "GitHub",12 "description": "Navbar item with label GitHub"13 },14 "item.label.Support Immer": {15 "message": "赞助 Immer",16 "description": "Navbar item with label Support Immer"17 }18}
modified:website/src/css/immer-infima.css+4 added
67 unmodified lines
6869iframe {70 border: none;71}7273.dropdown__link {74 color: black !important;75}
modified:website/docusaurus.config.js+9 added-1 removed
8 unmodified lines
9 organizationName: "immerjs",10 onBrokenLinks: "throw",11 onBrokenMarkdownLinks: "warn",12 favicon: "img/favicon.ico",13 i18n: {14 defaultLocale: 'en',15 locales: ['en', 'zh-CN'],16 },17 themeConfig: {18 googleAnalytics: {19 trackingID: "UA-65632006-3",20 anonymizeIP: true
21 unmodified lines
42 type: "doc",43 docId: "support",44 label: "Support Immer",45 position: "right"42 }46 },47 {48 type: 'localeDropdown',49 position: 'left',50 },51 ]52 },53 footer: {54 copyright: `Copyright © ${new Date().getFullYear()} Michel Weststrate`
34 unmodified lines