javascript - React 如何让 props 只读?

标签 javascript reactjs

我想知道他们在尝试设置 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/

相关文章:

javascript - 了解 "WhatsApp Web"前端页面是如何开发的

reactjs - 使用 testing-library 和 jest 的 React 组件抛出的测试错误

javascript - React 和 Flowtype - 继承类

javascript - NodeJS HTML 渲染策略

javascript - 滚动到自定义组件

javascript - 委托(delegate)函数在 jquery 2.1.1 中不起作用

javascript - 在 Vue.js 中传递参数

javascript - "Open Link in new Tab"不应打开 iFrame 源页面

javascript - 最大并发任务数为 "running"的异步任务管理器

javascript - React Router Redirect 丢弃参数