[英]Confused about return value in arrow function?
I found this code in one a tutorial.我在一个教程中找到了这段代码。
const renderApp = (Component) =>
render(
<Provider store={store}>
<AppContainer>
<Component />
</AppContainer>
</Provider>,
document.getElementById('root')
);
My question is shouldnt the return value be wrapped in braces?我的问题是返回值不应该用大括号括起来吗? because arrow functions return whats next to => if nothing is metnioned?
因为如果没有任何内容,箭头函数会返回 => 旁边的内容?
const renderApp = (Component) => (
render(
<Provider store={store}>
<AppContainer>
<Component />
</AppContainer>
</Provider>,
document.getElementById('root')
);
)
shouldn't it have braces to wrap contents?它不应该用大括号来包裹内容吗?
The right hand side of an arrow function can be either:箭头 function 的右侧可以是:
{
and }
(which are braces){
和}
(大括号)分隔return
statement in the block saysreturn
语句所说的任何内容You need to wrap the expression with parenthesis ( (
and )
) if it is an object literal because object literals are delimited with braces.如果表达式是 object 文字,则需要用括号(
(
和)
)括起表达式,因为 object 文字是用大括号分隔的。
() => { foo: 123, bar: 456 }; // This is an error
If you wrote the above, the {
and }
would be interpreted as a block and not an expression to create an object.如果您编写上面的代码,
{
和}
将被解释为一个块,而不是一个创建 object 的表达式。
() => ({ foo: 123, bar: 456 });
Adding parenthesis tells the JS parser that it is an expression and not a block.添加括号告诉 JS 解析器它是一个表达式而不是块。
Since your expression doesn't start with a {
, it won't be treated as a block so there is no need for parenthesis.由于您的表达式不是以
{
开头,因此不会将其视为块,因此不需要括号。
The first code snippet, after "=>" its empty, wont JS compiler insert;
第一个代码片段,在“=>”之后是空的,不会被 JS 编译器插入; and end it there?
然后就此结束?
No. Automatic semi-colon insertion only occurs in places which could be the end of something.不会。自动分号插入仅发生在可能是某物结尾的地方。 It won't happen in after
=>
because there must be something on the right-hand side of =>
.它不会发生在 after
=>
中,因为 = =>
的右侧必须有一些东西。
There's no need to wrap it within braces because a single line statement gets returned implicitly.不需要将它括在大括号中,因为单行语句会隐式返回。 You however can do it yourself, it isn't incorrect, just that it's a bit of syntactic sugar
但是你可以自己做,这并没有错,只是它有点语法糖
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.