Javascript对象解冻

修改 React props

React生成的对象是不能修改props的, 但实践中遇到需要修改props的情况. 如果直接修改, js代码将报错, 原因是props对象被冻结了, 可以用Object.isFrozen()来检测, 其结果是true. 说明该对象的属性是只读的.

那么, 有方法将props对象解冻, 从而进行修改吗?

事实上, 在javascript中, 对象冻结后, 没有办法再解冻, 只能通过克隆一个具有相同属性的新对象, 通过修改新对象的属性来达到目的.

可以这样:

  • ES6 Object.assign({}, frozenObject);
  • lodash _.assign({}, frozenObject);

来看实际代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
function modifyProps(component) {
let condictioin = this.props.condictioin,
newComponent = Object.assign({}, component),
newProps = Object.assign({}, component.props)

if (condictioin) {
if (condictioin.add) newProps.add = true
if (condictioin.del) newProps.del = true
}
newComponent.props = newProps

return newComponent
}

锁定对象的方法

  1. Object.preventExtensions()
    no new properties or methods can be added to the project
    对象不可扩展, 即不可以新增属性或方法, 但可以修改/删除
  2. Object.seal()
    same as prevent extension, plus prevents existing properties and methods from being deleted
    在上面的基础上,对象属性不可删除, 但可以修改
  3. Object.freeze()
    same as seal, plus prevent existing properties and methods from being modified
    在上面的基础上,对象所有属性只读, 不可修改

以上三个方法分别可用Object.isExtensible(), Object.isSealed(), Object.isFrozen()来检测

参考资料

Fork me on GitHub