当我有两个不可变的Map对象时:
const MapA = Immutable.fromJS({person: {name: 'Peter', age: 18}, parent: 'Sally'});
let MapB = Immutable.fromJS({prop1: 'testing'});
MapB = MapB.set('person', MapA.get('person'));
对象{name:'Peter',年龄:18}是在两张地图中分享还是有共享方式?
答案 0 :(得分:1)
ImmutableJS分享实例。在您的情况下,MapA和MapB共享快照实例person
。您可以通过在此实例上添加自定义纯JS属性来验证这一点,并对MapA版本和MapB版本进行验证。你会发现它们具有相同的值。
这里有一个小提琴...... https://jsfiddle.net/HaZardous/0Ls5gdht/。
这里是小提琴代码 -
var MapA = Immutable.fromJS({person: {name: 'Peter', age: 18}, parent: 'Sally'}),
MapB = Immutable.fromJS({prop1: 'testing'}),
person = MapA.get('person');
MapB = MapB.set('person', person);
person["nationality"] = "US";
console.log("Direct ref: " + person["nationality"]);
console.log("MapA ref: " + MapA.get('person')["nationality"]);
console.log("MapB ref: " + MapB.get('person')["nationality"]);
输出
Direct ref: US
MapA ref: US
MapB ref: US