如何在不复制全部字段时赋值对象?解决冻结对象赋值报错
解决Immutable/Frozen对象更新报错问题
嘿,这个问题我之前也碰到过!咱们先理清楚为啥会报错,再看怎么解决。
首先,你遇到的Attempting to set key on an object that is immutable and has been frozen错误,核心原因是this.currentRegion这个对象已经被**冻结(frozen)**了——这类对象的规则就是不允许直接修改它的任何属性,而你用Object.assign(this.currentRegion, coords)的时候,是直接在原冻结对象上修改属性,这就触发了限制。
正确的解决思路:创建新对象替代原对象
我们不需要去修改被冻结的原对象,而是生成一个全新的对象,把原currentRegion里需要保留的属性(latitudeDelta、longitudeDelta)和coords里的latitude、longitude合并起来,再赋值给this.currentRegion就行。
给你两种常用的写法:
写法1:ES6扩展运算符(更简洁)
// 从coords里提取需要的经纬度 const { latitude, longitude } = coords; // 生成新对象,合并原有delta配置和新经纬度 this.currentRegion = { ...this.currentRegion, latitude, longitude };
写法2:Object.assign(兼容旧环境)
// 把空对象作为第一个参数,避免修改原冻结对象 this.currentRegion = Object.assign({}, this.currentRegion, { latitude: coords.latitude, longitude: coords.longitude });
这两种方式都是生成全新的对象,完全避开了对冻结对象的修改操作,也就不会再报错啦。
补充:为啥原来的写法不行?
Object.assign(target, source)的逻辑是直接修改第一个参数target的属性,当target是被冻结的对象时,任何修改操作都会被运行时阻止,所以才会抛出那个错误。
内容的提问来源于stack exchange,提问作者Alice Bob
相关产品推荐
相关产品推荐

