为什么将 Arrow 函数体包裹在括号中
Why wrap Arrow function body in parentheses
在 survivejs 代码示例中,我遇到了一个主体包含在括号中的函数:
export default () => (
<ul>
{notes.map(note =>
//some code
)}
</ul>
)
MDN 是这样解释的:
// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
试图弄清楚这在现实世界的用例中究竟意味着什么。欢迎汽车类比(;
没有括号,对象声明括号{}
被认为是箭头函数体,会导致逻辑错误
这个params => { foo: 'bar'}
被认为是
params => {
foo: 'bar'
}
const func1 = params => { foo: 'bar'};
console.log(func1());
const func2 = params => ({ foo: 'bar'});
console.log(func2());
MDN 声明用于 return 对象文字。但我想你想知道为什么有些人不管对象字面量如何,都将 return 指令放在括号中。
一点理论
在JavaScript中是分号可选。如果您不知道自动分号插入的行为,这可能会导致一些错误。
当你有一个带换行符的 return
时,它将 return 一个 undefined
const add = (x, y) => {
return
x + y
}
console.log( add(1, 1) ) // undefined
自动分号插入做了一些神奇之后的等价物是:
const add = (x, y) => {
return;
x + y;
};
console.log( add(1, 1) );
但是,如果换行是必须的,例如,为了可读性..解决方案是将表达式括在括号中。
const add = (x, y) => {
return (
x + y
)
}
console.log( add(1, 1) ) // 2
您的用例
为了去掉括号,我们可以直接在 =>
之后提升 <ul>
标签。
const functionName = xs => <ul>
{xs.map(note =>
//some code
)}
</ul>
但现在它不再真正可读了..所以我们应该快速重新插入括号
const functionName = xs => (
<ul>
{xs.map( x =>
//some code
)}
</ul>
)
在 survivejs 代码示例中,我遇到了一个主体包含在括号中的函数:
export default () => (
<ul>
{notes.map(note =>
//some code
)}
</ul>
)
MDN 是这样解释的:
// Parenthesize the body of function to return an object literal expression: params => ({foo: bar})
试图弄清楚这在现实世界的用例中究竟意味着什么。欢迎汽车类比(;
没有括号,对象声明括号{}
被认为是箭头函数体,会导致逻辑错误
这个params => { foo: 'bar'}
被认为是
params => {
foo: 'bar'
}
const func1 = params => { foo: 'bar'};
console.log(func1());
const func2 = params => ({ foo: 'bar'});
console.log(func2());
MDN 声明用于 return 对象文字。但我想你想知道为什么有些人不管对象字面量如何,都将 return 指令放在括号中。
一点理论
在JavaScript中是分号可选。如果您不知道自动分号插入的行为,这可能会导致一些错误。
当你有一个带换行符的 return
时,它将 return 一个 undefined
const add = (x, y) => {
return
x + y
}
console.log( add(1, 1) ) // undefined
自动分号插入做了一些神奇之后的等价物是:
const add = (x, y) => {
return;
x + y;
};
console.log( add(1, 1) );
但是,如果换行是必须的,例如,为了可读性..解决方案是将表达式括在括号中。
const add = (x, y) => {
return (
x + y
)
}
console.log( add(1, 1) ) // 2
您的用例
为了去掉括号,我们可以直接在 =>
之后提升 <ul>
标签。
const functionName = xs => <ul>
{xs.map(note =>
//some code
)}
</ul>
但现在它不再真正可读了..所以我们应该快速重新插入括号
const functionName = xs => (
<ul>
{xs.map( x =>
//some code
)}
</ul>
)