当我尝试将 React 15.X 升级到 React 16.X 时出现问题:
let style = {
width:12
};
class Box extends React.Component {
constructor(props) {
super(props);
}
render() {
console.log(Object.getOwnPropertyDescriptor(style,'width'))
style.width = 96;
return (
<div style={style}>
</div>
);
}
}
输出:
- {value: 12, writable: true, enumerable: true, configurable: true}
- {value: 12, writable: false, enumerable: true, configurable: false}
- {value: 12, writable: false, enumerable: true, configurable: false}
有人知道为什么“可写”变成假了吗?
最佳答案
因为改变 style
对象是被禁止的,并且在渲染过程的某处,调用了 Object.freeze(style)
。
引用:
- > https://github.com/facebook/react/issues/11520#issuecomment-343731614
- > Why was mutating style deprecated?
长期以来一直不鼓励 React 中的对象突变。 Object.freeze(props)
在 v0.x.x 天后强制执行。在 v16 中添加了 Object.freeze(style)
。
关于javascript - 第一次渲染组件后,对象变为只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098114/