Immutable 入门

目的:

1.提高react render效率(shouldComponentUpdate 比较 imutable的前后两个props, 减少render次数,缩短生命周期,在)
2.所有数据都是一份新的,减少出错概率

文档:http://facebook.github.io/immutable-js/
安装

npm install immutable

基本创建及读取

const  {Map,List} = require('immutable'); 
var  map1 = Map({a:1,b:2,c:3});
console.log(map1.get("b"))
const list1 = List([ 1, 2 ]);
console.log(list1.get(1))

比较

const  {Map,List} = require('immutable');
var  map1 = Map({a:1,b:2,c:3});
var  map2 = map1.set("b",3);
var  map3 = map1.set("b",2);
var  map4 = Map({a:1,b:2,c:3});

// false  imutable 就是干这个的
console.log(map1===map2);
// 如果设置的值相同 ,则不改变,如下返回true,需要特别注意
console.log(map1===map3);
// 返回false
console.log(map1===map4);
// 值比较返回true
console.log(map1.equals(map4))

输出(toJS)及输入(fromJS)

const {fromJS} = require('immutable');
var map1 = fromJS({a: 1, b: 2, c: [1, 3, 4]});
// 输出1
console.log(map1.get("b"))
// 输出4
console.log(map1.get("c").get(2))
// 转化为原生js
console.log(map1.toJS())

多层次读写

const {fromJS} = require('immutable');
var map1 = fromJS({a: 1, b: 2, c: {d:3,e:4,f:{g:5,h:6}}});
// 读取 输出 6
console.log(map1.getIn(["c","f","h"]));
// 插入
console.log(map1.mergeDeep({c:{f:{x:99}}}));
// 更新
console.log(map1.updateIn(["c","f","h"],value=>value+1));

你可能感兴趣的:(react)