手写丐版immerjs:
const createProxy = (target) => {
const data = {
__initial: target,
__copy: null,
__isModified:false
}
const handler = {
get(state, attr) {
if(!state.__isModified)return state.__initial[attr]
if (state.__initial[attr] === 'object') {
if (state.__copy === null) {
state.__copy = {
...state.__initial
}
}
createProxy(state.__initial[attr])
}
return state.__copy[attr]
},
set(state, attr, value) {
state.__isModified = true
state.__copy = {
...state.__initial,
[attr]: value
}
}
}
const {
proxy
} =Proxy.revocable(data, handler)
return proxy
}
const immerjs = (data,cb)=>{
const res = createProxy(data)
cb(res)
return res
}
//使用案例
const obj = {
d:'wei',
a: {
b: {
c: {
name: 'weiz'
}
}
}
}
immerjs(obj,(data)=>{
console.log(data.b===obj.b);//true
data.b = {}
console.log(data.b===obj.b);//false
})
标签:.__,const,attr,immerjs,initial,state,丐版,data,手写
From: https://blog.csdn.net/cainiaoxianfeng/article/details/143165803