跳至主内容区

从草稿中提取当前状态

[非官方测试版翻译]

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

Immer 提供了一个名为 current 的命名导出,用于创建草稿当前状态的副本。这在调试时非常有用(因为这些对象不是 Proxy 对象,也不会以 Proxy 形式记录)。此外,对 current 的引用可以安全地从 produce 函数中泄露。简而言之,current 提供了草稿当前状态的快照。

current 生成的对象与 produce 自身创建的对象具有相似特性。

  1. 未修改的对象将与原始对象保持结构共享。

  2. 如果草稿未被修改,通常 original(draft) === current(draft) 成立,但这并非绝对保证。

  3. 草稿的后续修改不会反映在 current 生成的对象中(对不可草稿化对象的引用除外)。

  4. produce 不同,current 创建的对象不会被冻结。

请谨慎使用 current,这可能是一项开销较大的操作,尤其是在 ES5 环境下。

请注意 current 不能对非草稿对象调用。

示例

以下示例展示了 current(及 original)的效果:

const base = {
x: 0
}

const next = produce(base, draft => {
draft.x++
const orig = original(draft)
const copy = current(draft)
console.log(orig.x)
console.log(copy.x)

setTimeout(() => {
// this will execute after the produce has finished!
console.log(orig.x)
console.log(copy.x)
}, 100)

draft.x++
console.log(draft.x)
})
console.log(next.x)

// This will print
// 0 (orig.x)
// 1 (copy.x)
// 2 (draft.x)
// 2 (next.x)
// 0 (after timeout, orig.x)
// 1 (after timeout, copy.x)