使用proxy实现immutable

2020-08-28  本文已影响0人  月_关

什么是immutable

如果需要频繁的操作一个复杂对象,每次完全拷贝一次的效率太低了。大部分场景下都只是更新了对象的一两个字段,其他字段都不变,对于这些不变的字段的拷贝都是多于的。

immutable就可以实现仅仅拷贝修改的值, 这样在React项目中,可以很好的优化性能

我们来用proxy实现一个简单按需拷贝


let obj = {
        a:1,
        c:{
            value:1
        }
    }

    class Store {
        constructor(state) {
            // 是否改动过数据
            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'

    // 转发配置
    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)
        // 执行传入的回调方法
        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

上一篇 下一篇

猜你喜欢

热点阅读