亲宝软件园·资讯

展开

Proxy的不可变数据优点及使用详解

云牧 人气:0

可变数据

不可变数据(Immutable Data)

优点

实现一:独立方法

function updateData(obj, key, value) {
  return {
    ...obj,
    [key]: value
  };
}
const obj = {
  name: "云牧"
};
const newObj = updateData(obj, "name", "黛玉");
console.log(newObj); // { name: '黛玉' }
console.log(obj); // { name: '云牧' }

实现二:自定义对象

class MyObject {
  constructor(obj = {}) {
    this.obj = { ...obj };
  }
  get(name) {
    return this.obj[name];
  }
  set(name, value) {
    return new MyObject({
      ...this.obj,
      [name]: value
    });
  }
}
const obj = new MyObject({
  name: "云牧"
});
const newObj = obj.set("name", "黛玉");
console.log(newObj); // MyObject { obj: { name: '黛玉' } }
console.log(obj); // MyObject { obj: { name: '云牧' } }

实现三:函数 + 复制

function produce(obj, recipe) {
  const newObj = { ...obj };
  recipe(newObj);
  return newObj;
}
const obj = {
  name: "云牧"
};
const newObj = produce(obj, draft => {
  draft.name = "黛玉";
});
console.log(newObj); // { name: '黛玉' }
console.log(obj); // { name: '云牧' }

实现四:Proxy代理

function produce(obj, recipe) {
  const state = {
    base: obj, // 基础对象
    copy: {}, // 被更改后的对象
    draft: {}, // 代理对象
    currentKey: 0 // 当前操作的key
  };
  const handlerItem = {
    get(target, property, receiver) {
      // 如果更改后的对象存在则使用copy
      if (state.copy[state.currentKey]) {
        return state.copy[state.currentKey][property];
      }
      return state.base[state.currentKey][property];
    },
    set(target, property, value, receiver) {
      Reflect.set(state.copy[state.currentKey], property, value);
    }
  };
  const handler = {
    get(target, property, receiver) {
      state.currentKey = property;
      if (!state.draft[property]) {
        const val = { ...state.base[property] };
        const proxy = new Proxy(val, handlerItem);
        state.draft[property] = proxy;
        state.copy[property] = val;
      }
      return state.draft[property];
    },
    set(target, property, value, receiver) {
      return Reflect.set(state.copy, property, value);
    }
  };
  const proxyObj = new Proxy(obj, handler);
  recipe(proxyObj);
  return proxyObj;
}
const arrObj = Array.from({ length: 100 }, (v, index) => ({ name: "云牧" + index }));
const newObj = produce(arrObj, draft => {
  draft[50].name = "黛玉";
});
console.log(newObj[50].name); // 黛玉
console.log(arrObj[50].name); // 云牧50

实现五:第三方不可变对象

加载全部内容

相关教程
猜你喜欢
用户评论