Immutable.js 进行js的复制

介绍

在提供不可变(Immutable)数据结构的支持。不可变数据是指一旦创建后就不能被修改的数据,每次对数据进行更新都会返回一个新的数据对象,而原始数据保持不变。

使用

日常中我们使用的拷贝

(1) var arr = { } ; arr2 = arr ;
(2) Object.assign() 只是一级属性复制,比浅拷贝多拷贝了一层而已。
(3) const obj1 = JSON.parse(JSON.stringify(obj)); 数组,对象都好用的方法 ( 缺点 : 不能有 undefined)

原理

Immutable 实现的原理是 Persistent Data Structure(持久化数据结构),也就是使用旧数据创建新数据时,要保证旧数据同时可用且不变。同时为了避免 deepCopy 把所有节点都复制一遍带来的性能损耗, Immutable 使用 了 Structural Sharing(结构共享),即如果对象树中一个节点发生变化,只修改这个节点和受它影响的父节点, 其它节点则进行共享。


使用方式


Map:

const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
map1.get('b') + " vs. " + map2.get('b'); // 2 vs. 50

List:

const { List } = require('immutable');
const list1 = List([ 1, 2 ]);
const list2 = list1.push(3, 4, 5);
const list3 = list2.unshift(0);
const list4 = list1.concat(list2, list3);
assert.equal(list1.size, 2);
assert.equal(list2.size, 5);
assert.equal(list3.size, 6);
assert.equal(list4.size, 13);
assert.equal(list4.get(0), 1);
//push, set, unshift or splice 都可以直接用,返回一个新的immutable对象
merge , concat
const { Map, List } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3, d: 4 });
const map2 = Map({ c: 10, a: 20, t: 30 });
const obj = { d: 100, o: 200, g: 300 };
const map3 = map1.merge(map2, obj);
// Map { a: 20, b: 2, c: 10, d: 100, t: 30, o: 200, g: 300 }
const list1 = List([ 1, 2, 3 ]);
const list2 = List([ 4, 5, 6 ]);
const array = [ 7, 8, 9 ];
const list3 = list1.concat(list2, array);
// List [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Immutable+Redux的开发方式

//reducer.js
const initialState = fromJS({
category:"",
material:""
})
const reducer = (prevstate = initialState,action={})=>{
let {type,payload} = action
switch(type){
case GET_HOME:
var newstate =prevstate.set("category",fromJS(payload.category))
var newstate2 =newstate.set("material",fromJS(payload.material))
return newstate2;
default:
return prevstate
}
}
//home.js
const mapStateToProps = (state)=>{
return {
category:state.homeReducer.getIn(["category"]) || Map({}),
material:state.homeReducer.getIn(["material"]) || Map({})
}
}
this.props.category.get("相关属性")
this.props.category.toJS() //或者转成普通对象

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值