admin管理员组

文章数量:1429844

I'm still unfamiliar with all the magic of ES6. I saw this code in an online article and I'm not sure how PrivateRoute is destructuring the input props. what does ponent: Component do in this context?

const PrivateRoute = ({ ponent: Component, ...rest }) => (
  // Code here
)

I understand that I can do something like this to destructure an object

obj = {firstName: 'John', lastName: 'Doe'};
{first, last} = obj;

and have first = 'John', last = 'Doe'; however, I got confused with the introduction of a colon in the example code.

Here's a link to the full article: /

I'm still unfamiliar with all the magic of ES6. I saw this code in an online article and I'm not sure how PrivateRoute is destructuring the input props. what does ponent: Component do in this context?

const PrivateRoute = ({ ponent: Component, ...rest }) => (
  // Code here
)

I understand that I can do something like this to destructure an object

obj = {firstName: 'John', lastName: 'Doe'};
{first, last} = obj;

and have first = 'John', last = 'Doe'; however, I got confused with the introduction of a colon in the example code.

Here's a link to the full article: https://tylermcginnis./react-router-protected-routes-authentication/

Share Improve this question asked Jun 12, 2018 at 21:59 YSAYSA 8792 gold badges15 silver badges33 bronze badges 1
  • 3 Read the docs: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – CertainPerformance Commented Jun 12, 2018 at 22:01
Add a ment  | 

2 Answers 2

Reset to default 7

There are two basic ways to use the : in destructuring:

  1. destructuring sub objects
  2. aliasing a variable

If the right hand side of the : is an object or array then you are destructuring a sub-object. If the right hand side is an identifier then you are aliasing the key on the left hand side of the :

Destructuring Sub Objects

const { ponent: { example } } = opts

// equivalent to
const example = opts.ponent.example

Aliasing a Variable

const { ponent: Component } = opts

// equivalent to:
const Component = opts.ponent

Both Combined

const { ponent: { example: Component } } = opts

// equivalent to
const Component = opts.ponent.example

It's to use a different name for a property obtained by destructuring.

let obj = {
  a: 'thing A',
  b: 'thing B'
}

let { a: newVariable } = obj
console.log(newVariable) // outputs: "thing A"

See MDN docs for Assigning to new variable names

本文标签: javascriptUsing colons within object destructuringStack Overflow