在反应中破坏道具的不同方式

Different ways of destructuring props in react

我见过两种在 React 中解构 props 的方法。

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

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

假设这个组件用作

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

这是我的问题:

如果我用的是第一种解构方式,是不是意味着我将无法接触到其他亲,在这种情况下haspets

这两种方式有哪些pros/cons?

如果你从函数参数中解构你的道具,你以后将无法访问任何其他 props**,所以你的假设是正确的。就性能和其他 pros/cons 而言,这些形式几乎相同。我碰巧喜欢这种方式,因为我喜欢在我的文件中尽可能少地声明额外的变量。对于需要大量道具的功能来说,这可能会很痛苦。

**除非你使用展开运算符并将它们存储在一个单独的变量中。

您稍后可以通过 the arguments object 访问对象的其他属性,但正如 link 上也指出的那样,其余参数应该是首选。

<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 }
}

我能想到的差异之一,我想 最重要的,是在第二种情况下,当你正在破坏你的 props 对象时,您在声明中使用了 const

这样,您就无法再在 MyComponent 上更改这些值,而在第一种情况下,您可以轻松修改它们。