为什么将 Arrow 函数体包裹在括号中

Ska*_*ski 3 javascript return ecmascript-6 reactjs arrow-functions

survivaljs代码示例中,我遇到了一个函数,其主体用括号括起来:

export default () => (
  <ul>
      {notes.map(note =>
          //some code
      )}
  </ul>
)
Run Code Online (Sandbox Code Playgroud)

MDN 是这样解释的:

// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
Run Code Online (Sandbox Code Playgroud)

试图弄清楚这在现实世界用例中的实际含义。欢迎使用汽车类比 (;

Sur*_*yan 6

如果没有括号,对象声明括号{}将被视为箭头函数体,这会导致逻辑错误。

params => { foo: 'bar'}被认为是

params => { 
             foo: 'bar'
          }
Run Code Online (Sandbox Code Playgroud)

params => { 
             foo: 'bar'
          }
Run Code Online (Sandbox Code Playgroud)


Rom*_*man 5

MDN 声明用于返回对象字面量。但是我想您想知道为什么有些人将 return 指令放在括号中,而不管对象文字如何。

一点理论

在 JavaScript 中,分号是可选的。如果您不知道自动分号插入的行为,这可能会导致一些错误。

当你有一个return换行符时,它会返回一个undefined

const add = (x, y) => {
  return
    x + y
}

console.log( add(1, 1) )  // undefined
Run Code Online (Sandbox Code Playgroud)

自动分号插入后的等价物是:

const add = (x, y) => {
  return;
  x + y;
};

console.log( add(1, 1) );
Run Code Online (Sandbox Code Playgroud)

但是如果换行是必须的,例如,为了可读性……解决方案是将表达式包装在括号中。

const add = (x, y) => {
  return (
    x + y
  )
}

console.log( add(1, 1) ) // 2
Run Code Online (Sandbox Code Playgroud)

您的用例

为了去掉括号,我们可以<ul>直接在=>.

const functionName = xs => <ul>
    {xs.map(note =>
        //some code
    )}
</ul>
Run Code Online (Sandbox Code Playgroud)

但是现在它不再可读了..所以我们应该快速重新插入括号

const functionName = xs => (
    <ul>
        {xs.map( x =>
            //some code
        )}
    </ul>
)
Run Code Online (Sandbox Code Playgroud)