Immutable.js 引用相等性

标签 immutable.js

给出以下简单代码:

const Immutable = require('immutable');
const a = Immutable.fromJS({
    a: 1,
    b: [2, 3, 4],
    c: {
        d: 1
    }
});
const b = a.setIn(['c', 'd'], "Something else");
const c = b.setIn(['c', 'd'], 1);

console.log(a.equals(b)); // true
console.log(Immutable.is(a, c)); // true
console.log(a === c); // false?

对于最终的比较,我希望它返回 true,因为我将路径 ['c', 'd'] 设置为其他内容,然后返回原始值,通过结构共享,我希望它会导致 c 保留对原始数据结构的引用?

我是否误解了它的工作原理?

最佳答案

首先,这个 console.log(a.equals(b)); 实际上返回 false:

现在回答你的问题,如 Immutable.js here 中所述在“无操作优化时返回自身”子章节:

When possible, Immutable.js avoids creating new objects for updates where no change in value occurred, to allow for efficient reference equality checking to quickly determine if no change occurred.

有一个例子:

const { Map } = require('immutable');
const originalMap = Map({ a: 1, b: 2, c: 3 });
const updatedMap = originalMap.set('b', 2);
updatedMap === originalMap; // No-op .set() returned the original reference.

However updates which do result in a change will return a new reference. Each of these operations occur independently, so two similar updates will not return the same reference:

那个例子:

const { Map } = require('immutable');
const originalMap = Map({ a: 1, b: 2, c: 3 });
const updatedMap = originalMap.set('b', 1000);
// New instance, leaving the original immutable.
updatedMap !== originalMap;
const anotherUpdatedMap = originalMap.set('b', 1000);
// Despite both the results of the same operation, each created a new reference.
anotherUpdatedMap !== updatedMap;
// However the two are value equal.
anotherUpdatedMap.equals(updatedMap);

由于您要更改值,setIn 返回一个新引用。因此,通过引用它们并不相等。

希望我有帮助:)

关于Immutable.js 引用相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54272331/

相关文章:

javascript - 从 Map 转换为 List ImmutableJS 时维护键值

javascript - 使用 ImmutableJS Record 创建具有不同属性的子类

javascript - Typescript 函数转换为 Immutable.js Typescript 列表

javascript - 使用 ngrx 或 ngxs 时,我们会自动获得对象不变性吗?

node.js - Immutablejs Map.update 破坏了单元测试

javascript - 使用不可变的js将reducer状态设置为返回的数组

javascript - immutable.js & react.js setState 清除对象原型(prototype)

javascript - Immutable.js 允许对象发生变化

javascript - 在 Immutable.js 中获取嵌套值