官术网_书友最值得收藏!

Passing Immutable.js collections

Another scenario for passing data to Immutable.js constructors is for passing other Immutable.js collections. For example, let's say that you have a map instance, just like the one that we created in the preceding section. You can then do the following:

const firstMap = Map({ a: 1, b: 2, c: 3 });
console.log('myMap', myMap.get('a'));
// -> myMap 1

As expected, you get a new map instance in the firstMap constant. Now let's use this first instance as the input for creating another map:

const myMap = Map(firstMap);
console.log('firstMap === myMap', firstMap === myMap);
// -> firstMap === myMap true

Wait, if Immutable.js maps are immutable, how can firstMap be the same reference as myMap? This is a trick that Immutable.js uses to avoid having to create another instance of the exact same collection. By doing this, you're not actually violating any kind of immutability constraints. The collection that is passed to Map() can't change, so creating a copy of it is wasteful.

This can be useful if you're creating a function that accepts a collection as an argument:

const myFunc = map => Map(map).toJS();

console.log('myFunc(object)', myFunc({ a: 1, b: 2, c: 3 }));
// -> myFunc(object) { a: 1, b: 2, c: 3 }
console.log('myFunc(map)', myFunc(myMap));
// -> myFunc(map) { a: 1, b: 2, c: 3 }
Rule of thumb: it's never a bad idea to wrap a collection in a collection constructor so that you get consistent results.
主站蜘蛛池模板: 吉木萨尔县| 黄梅县| 安远县| 仪陇县| 洮南市| 宁强县| 南丰县| 板桥市| 肥东县| 宜丰县| 阿克| 麻城市| 永和县| 大洼县| 宁津县| 革吉县| 光泽县| 洛扎县| 黄大仙区| 周口市| 双流县| 西青区| 新河县| 固安县| 轮台县| 定边县| 申扎县| 丰原市| 云和县| 南开区| 南开区| 丹寨县| 玉山县| 杨浦区| 兴化市| 太白县| 霍山县| 依兰县| 宁远县| 鄂伦春自治旗| 准格尔旗|