简体   繁体   English

在 React 中解构 props 的不同方式

[英]Different ways of destructuring props in react

I have seen two ways to destructure props in React.我见过两种在 React 中解构 props 的方法。

    function MyComponent({name,age,height}){
            // do stuff here
    }

or或者

    function MyComponent(props){
            const {name,age,height} = props
            // do stuff here
    }

Suppose this component is used as假设这个组件被用作

<MyComponent name="bob" age={25} height = {175} haspets={false}/>

Here is my questions:这是我的问题:

If I used the first way of destructuring, does it mean that I will have no access to other pros, in this case haspets如果我使用第一种解构方式,是否意味着我将无法访问其他专业人士,在这种情况下是haspets

What are some pros/cons of these two ways?这两种方式的优缺点是什么?

You can have access on the other properties of your object later, throught the arguments object , though as also pointed out on the link the rest parameters should be prefered.您可以稍后通过 arguments object访问对象的其他属性,但正如链接中所指出的那样,应该首选其余参数。

<MyComponent name="bob" age={25} height = {175} surname="test" haspets={false} />

function MyComponent({ name, age, height, ...rest }){
      // rest will be an object like { surname: 'test', haspets: false }
}

One of the differences I can think of, and I suppose the most important , is that on the second case, while you are destructing your props object, you are using const on declaration.我能想到的差异之一,我认为最重要的是,在第二种情况下,当您破坏props对象时,您在声明时使用了const

In that way, you can no longer change these values on your MyComponent , while on your first case you could easily modify them.这样,您就无法再更改MyComponent上的这些值,而在第一种情况下,您可以轻松修改它们。

If you destructure your props from the function parameters, you won't be able to access any other props later on**, so your assumption is correct.如果你从函数参数中解构你的 props,你以后将无法访问任何其他props **,所以你的假设是正确的。 As far as performance and other pros/cons though, these forms are pretty much identical.就性能和其他优点/缺点而言,这些形式几乎相同。 I happen to like this way, because I like as few additional variable declarations in my files as possible.我碰巧喜欢这种方式,因为我喜欢尽可能少地在我的文件中添加额外的变量声明。 It can, be a pain with functions that require lots of props.对于需要大量道具的功能来说,这可能会很痛苦。

**Unless you use the spread operator and store them in a separate variable. **除非您使用扩展运算符并将它们存储在单独的变量中。

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

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