什么是immutable
如果需要頻繁的操作一個復(fù)雜對象,每次完全拷貝一次的效率太低了。大部分場景下都只是更新了對象的一兩個字段,其他字段都不變,對于這些不變的字段的拷貝都是多于的。
immutable就可以實現(xiàn)僅僅拷貝修改的值, 這樣在React項目中,可以很好的優(yōu)化性能
我們來用proxy實現(xiàn)一個簡單按需拷貝
let obj = {
a:1,
c:{
value:1
}
}
class Store {
constructor(state) {
// 是否改動過數(shù)據(jù)
this.modified = false;
// 記錄原對象
this.source = state;
// 記錄改動的值
this.copy = null;
}
get (key) {
if (!this.modified) return this.source[key]
return this.copy[key]
}
set (key, value) {
if (!this.modified) this.modifing()
return this.copy[key] = value
}
modifing () {
if (this.modified) return
this.modified = true
this.copy = Array.isArray(this.source) ? this.source.slice() : {...this.source}
}
}
const FLAG = 'FLAG'
// 轉(zhuǎn)發(fā)配置
const handler = {
get (target, key) {
if (key === FLAG) return target
return target.get(key)
},
set (target, key, value) {
return target.set(key, value)
}
}
function produce (state, producer) {
const store = new Store(state)
const proxy = new Proxy(store, handler)
// 執(zhí)行傳入的回調(diào)方法
producer(proxy)
// 獲取新的對象
const newState = proxy[FLAG]
// 查看對象是否改動
if (newState.modified) return newState.copy
return newState.source
}
let newObj = produce(obj, drat => {
drat.a = {
value:123
}
})
console.log(newObj.c === obj.c) // true