Parsing error: Unexpected token const
Parsing error: Unexpected token const
我目前正在设置一个 meteor 应用程序,我正在使用 eslint 和 babel,但我收到以下代码片段的以下错误:
const Navigation = props => (
const classes = props.classes;
return (
<div className={classes.root}>
</div>
)
);
错误:
2:4 - Parsing error: Unexpected token const
我重新创建了我的 eslint 配置 here。
我的 .babelrc 配置如下:
{
"presets": ["env", "react"]
}
这是因为您正在使用 arrow function 的 concise body
并且需要 ()
中的表达式而不是语句。要使用语句,您需要通过使用 {}
而不是 ()
.
来使用 block body
像这样:
const Navigation = props => {
const classes = props.classes;
return (
<div className={classes.root}>
</div>
)
};
根据MDN Doc:
Arrow functions can have either a "concise body" or the usual "block
body".
In a concise body, only an expression is needed, and an implicit
return is attached. In a block body, you must use an explicit return
statement.
@Mayank Shukla 有解决办法,但我想补充一点,你也可以这样做:
const Navigation = ({classes}) => (
<div className={classes.root}>
</div>
);
({classes})
部分称为“对象解构”,基本上意味着您从函数接收的 props
参数中提取 classes
属性。
您可以使用任意数量的参数执行此操作。例如:
const Navigation = ({classes, children}) => (
<div className={classes.root}>
{children}
</div>
);
查看 MDN documentation 了解更多信息:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
我目前正在设置一个 meteor 应用程序,我正在使用 eslint 和 babel,但我收到以下代码片段的以下错误:
const Navigation = props => (
const classes = props.classes;
return (
<div className={classes.root}>
</div>
)
);
错误:
2:4 - Parsing error: Unexpected token const
我重新创建了我的 eslint 配置 here。 我的 .babelrc 配置如下:
{
"presets": ["env", "react"]
}
这是因为您正在使用 arrow function 的 concise body
并且需要 ()
中的表达式而不是语句。要使用语句,您需要通过使用 {}
而不是 ()
.
block body
像这样:
const Navigation = props => {
const classes = props.classes;
return (
<div className={classes.root}>
</div>
)
};
根据MDN Doc:
Arrow functions can have either a "concise body" or the usual "block body".
In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.
@Mayank Shukla 有解决办法,但我想补充一点,你也可以这样做:
const Navigation = ({classes}) => (
<div className={classes.root}>
</div>
);
({classes})
部分称为“对象解构”,基本上意味着您从函数接收的 props
参数中提取 classes
属性。
您可以使用任意数量的参数执行此操作。例如:
const Navigation = ({classes, children}) => (
<div className={classes.root}>
{children}
</div>
);
查看 MDN documentation 了解更多信息:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.