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

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.
主站蜘蛛池模板: 马尔康县| 凌源市| 奇台县| 湟源县| 蓬安县| 安平县| 郯城县| 兴和县| 沁阳市| 旬阳县| 台州市| 马龙县| 吴堡县| 渭南市| 澳门| 无为县| 和林格尔县| 水城县| 揭西县| 桂平市| 新安县| 确山县| 泌阳县| 新巴尔虎右旗| 德阳市| 雅江县| 麟游县| 乌恰县| 施甸县| 福鼎市| 深水埗区| 汾西县| 页游| 德州市| 诏安县| 电白县| 弋阳县| 芦溪县| 手游| 阳西县| 利辛县|