简体   繁体   English

反应js如何确保道具的不变性?

[英]How does react js ensure immutability of props?

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara"/>;

I have this in jsx. 我在jsx中有这个。

It compiles to this js: 它汇编到这个js:

function Welcome(props) {
  return __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement(
    "h1",
    {
      __source: {
        fileName: _jsxFileName,
        lineNumber: 7
      },
      __self: this
    },
    "Hello, ",
    props.name
  );
}

var element = __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement(Welcome, { name: "Sara", __source: {
    fileName: _jsxFileName,
    lineNumber: 10
  },
  __self: this
});

It looks like normal js to me. 对我来说,它看起来像普通的js。

在此输入图像描述

So I put a break point here in chrome. 所以我在Chrome中提出了一个断点。

When it ran to that break point, I went to chrome's console and did this: 当它跑到那个断点时,我去了chrome的控制台并做了这个: 在此输入图像描述

These 3 expressions were typed into the console and executed when the break point was on. 这3个表达式被输入控制台并在断点开启时执行。

It seems like I really can not change properties of the variable named props. 看来我真的无法改变名为props的变量的属性。

But the props object looks like an innocent object, how is this implemented in react js? 但道具对象看起来像一个无辜的对象,这是如何在反应js中实现的?

The source code 源代码

 // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source, }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } 

The props are created using Object.defineProperty which gives you and ability to set writable: false and then "freezing" it with Object.freeze : 使用Object.defineProperty创建props ,它使您能够设置writable: false ,然后使用Object.freeze “冻结”它:

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; Object.freeze()方法冻结一个对象:即阻止向其添加新属性; prevents existing properties from being removed; 防止删除现有属性; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. 并防止现有属性或其可枚举性,可配置性或可写性被更改。 The method returns the object in a frozen state. 该方法返回处于冻结状态的对象。

JSFiddle brief example (open the console before running): https://jsfiddle.net/rttw629v/ JSFiddle简要示例(运行前打开控制台): https ://jsfiddle.net/rttw629v/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM