我想知道他们在尝试设置 this.props.a = 1
或类似内容时实际使用什么机制来抛出错误。
我问是因为在记录 props 时我没有看到像 [Getter/Setter]
这样的东西,我认为这是他们在做什么。
谢谢!
最佳答案
好问题。
我认为props
是一种对象值,被标记为const
。
但我们可以更改任何 Object
值中的子项,即使它被标记为 const
;
// const also works on objects
const MY_OBJECT = {'key': 'value'};
// Attempting to overwrite the object throws an error - Uncaught TypeError: Assignment to constant variable.
MY_OBJECT = {'OTHER_KEY': 'value'};
// However, object keys are not protected,
// so the following statement is executed without problem
MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable
正如您在上面的代码中看到的,您可以使用 Object.freeze()使对象不可变的函数。
我认为 props
值设置为 Object.freeze()
函数。
关于javascript - React 如何让 props 只读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45129359/