[英]Why wrap Arrow function body in parentheses
In a survivejs code example I encountered a function with a body wrapped in parentheses: 在一个Survivaljs代码示例中,我遇到了一个函数,该函数的主体用括号括起来:
export default () => (
<ul>
{notes.map(note =>
//some code
)}
</ul>
)
MDN explains it like this: MDN这样解释:
// Parenthesize the body of function to return an object literal expression: params => ({foo: bar})
Trying to figure out what this actually means in a real world use case. 试图弄清楚在实际用例中这实际上意味着什么。 Car analogies welcome (;
汽车类比欢迎(;
Without parenthesis, the object declaration brackets {}
are considered as the arrow function body which will lead a logic error. 如果没有括号,则将对象声明括号
{}
视为箭头函数体,这将导致逻辑错误。
This params => { foo: 'bar'}
is considered as 此
params => { foo: 'bar'}
被认为是
params => {
foo: 'bar'
}
const func1 = params => { foo: 'bar'}; console.log(func1()); const func2 = params => ({ foo: 'bar'}); console.log(func2());
The MDN declaration is used to return an object literal. MDN声明用于返回对象文字。 But I think you want to know why some people put the return instruction in parentheses regardless of the object literals.
但是我想您想知道为什么有些人不管对象字面量如何都将返回指令放在括号中。
In JavaScript are semicolons optional . 在JavaScript中,分号是可选的 。 This can cause some errors if you dont know the behavior of the Automatic Semicolon Insertion.
如果您不知道自动分号插入的行为,则可能会导致一些错误。
When you have a return
with a line break it will return an undefined
当您有换行符
return
时,它将返回一个undefined
const add = (x, y) => { return x + y } console.log( add(1, 1) ) // undefined
The equivalent after the Automatic Semicolon Insertion does some magic is: 自动分号插入后的等效功能是:
const add = (x, y) => { return; x + y; }; console.log( add(1, 1) );
But what if the line break is a must, for example, for readability .. The solution is to wrap the expression into parentheses. 但是,例如,为了提高可读性 ,如果必须换行,该怎么办。解决方案是将表达式包装在括号中。
const add = (x, y) => { return ( x + y ) } console.log( add(1, 1) ) // 2
To get rid of the parentheses we could lift up the <ul>
tag directly after the =>
. 为了摆脱括号,我们可以在
=>
之后直接抬起<ul>
标签。
const functionName = xs => <ul>
{xs.map(note =>
//some code
)}
</ul>
But now it is not really readable anymore.. so we should reinsert the parentheses quickly 但是现在它不再真正可读了..所以我们应该快速重新插入括号
const functionName = xs => (
<ul>
{xs.map( x =>
//some code
)}
</ul>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.