且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否通过props将对象传递给子反应组件,克隆原始对象或通过引用传递?

更新时间:2023-11-10 08:27:22

通常,它取决于所述道具的数据类型。基元(例如整数字符串)按其值传递,而对象数据类型(如数组)则通过其引用向下传递。

In general, it depends on the data-type of said prop. Primitives, such as integers or Strings are passed down by their value, while Object data-types such as arrays are passed down by their reference.

所以是的, Objects 特别是通过引用向下传递。

So yes, Objects specifically are passed down by reference.

演示:

在此演示中,我们有两个组件,一个父组件和一个子组件。孩子有两个道具,一个是整数 1 ,另一个是的对象a:foo

In this demo we have two components, one parent and one child. The child takes two props, one that is the integer 1 and the other is an object with a: "foo".

过了一会儿,从父母那里我们将整数值从 1 更改为 2 和来自的对象a:foo a:bar 。之后,我们从子组件中记录这些道具的值。

After a short while, from the parent we change the integers value from 1 to 2 and the object from a: "foo" to a: "bar". After that, we log the values of these props from the child component.

输出仍为 1 整数(没有改变 - 按值传递),但 a:对象的bar(已更改! - 通过引用传递)。

The output is still 1 for the integer (didn't change - passed by value), but a: "bar" for the object (changed! - passed by reference).

const Parent = () => { 
  let myInt = 1;
  let myObj = {a: "foo"};
  setTimeout(function(){
    myInt = 2;
    myObj.a = "bar";
  }, 500);
 
  return <Child myInt={myInt} myObj={myObj} />;
}

const Child = ({myInt, myObj}) => {
  setTimeout(function(){
    console.log(myInt);
    console.log(myObj);
  }, 1000);
  
  return (
    <div>
      <p>{myInt}</p>
      <p>{JSON.stringify(myObj)}</p>
    </div>
  );
}
 
ReactDOM.render(<Parent />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>