Is var { Route, Redirect, RouteHandler, Link } = R

2020-08-09 09:41发布

问题:

What does this mean in Javascript ? I found this in react-router examples

var { Route, Redirect, RouteHandler, Link } = Router;

I get the following error when it is run through browserify.

"Uncaught SyntaxError: Unexpected token {"

https://github.com/rackt/react-router/blob/master/examples/dynamic-segments/app.js

Esprima also gives the same error: http://esprima.org/demo/validate.html

回答1:

Apparently it's called a destructuring assignment.

From another post here:

{x, y} = foo;

is equivalent to

x = foo.x;
y = foo.y;

This is part of ECMAScript 6, and Facebook's JSX transform has an optional flag to enable transpiling select ES6 syntax (including destructuring) to ES5-compatible syntax, which react-router uses.

Here is the original post with answer by Mike Christensen:

What do {curly braces} around javascript variable name mean



回答2:

It worked after changing my code to

var Route = Router.Route;
var RouteHandler = Router.RouteHandler;
var Link = Router.Link;

More information about this can be found here: http://facebook.github.io/react/docs/transferring-props.html#transferring-with-...-in-jsx



回答3:

That's a JSX file, not JavaScript. It was invented by Facebook as part of React.js. It gets compiled into a JavaScript file before execution. The file had @jsx pragma in the previous commit: https://github.com/rackt/react-router/commit/3abe98444481598beef22d3af2bf01effc556c6b

JSX allows to do things like this:

// Using JSX to express UI components.
var dropdown =
  <Dropdown>
    A dropdown list
    <Menu>
      <MenuItem>Do Something</MenuItem>
      <MenuItem>Do Something Fun!</MenuItem>
      <MenuItem>Do Something Else</MenuItem>
    </Menu>
  </DropDown>;

render(dropdown);

and this

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.render(<HelloMessage name="John" />, mountNode);