关于javascript:没有花括号的箭头功能

Arrow function without curly braces

我是ES6和React的新手,我一直在看箭头功能。 为什么有些箭头函数在胖箭头之后使用花括号而有些使用括号?
例如:

1
2
3
4
5
6
7
const foo = (params) => (
    <span>
        <p>
Content
</p>
    </span>
);

1
2
3
4
const handleBar = (e) => {
    e.preventDefault();
    dispatch('logout');
};

谢谢你的帮助!


括号返回单个值,花括号执行多行代码。

您的示例看起来很混乱,因为它使用的JSX看起来像多个"行",但实际上只是编译为单个"元素"。

以下是一些例子,它们都做同样的事情:

1
2
3
4
5
6
7
8
9
const a = (who) =>"hello" + who +"!";
const b = (who) => (
   "hello" +
    who +
   "!"
);
const c = (who) => {
  return"hello" + who +"!";
};

您还经常会看到围绕对象文字的括号,因为这是一种避免解析器将其视为代码块的方法:

1
2
const x = () => {} // Does nothing
const y = () => ({}) // returns an object


也可以使用花括号来防止单行箭头函数返回一个值 - 或者让下一个开发人员明白单行箭头函数不应该返回任何东西。

例如:

1
2
3
4
5
const myFunc = (stuff) => { someArray.push(stuff) }
const otherFunc = (stuff) => someArray.push(stuff)

console.log(myFunc())    // --> logs undefined
console.log(otherFunc()) // --> logs result of push which is new array length


实际上在公文包中有人在箭头函数声明中使用大括号时,它等于下面:

1
2
3
4
5
6
7
8
9
10
11
12
13
const arrow = number => number + 1;

|||

const arrow = (number) => number + 1;

|||    

const arrow = (number) => ( number + 1 );

|||

const arrow = (number) => { return number + 1 };

在第一个示例中,箭头函数的右侧显示由分组运算符包围的单个表达式:

1
2
3
4
5
6
7
const foo = (params) => (
  <span>
    <p>
Content
</p>
  </span>
);

类似的可比案例如下:

1
2
3
const foo = (params) => (<span><p>
Content
</p></span>);

在上述使用单个表达式的情况下,区别在于右侧是函数的返回值。

另一方面,如果你使用花括号,JavaScript将理解为一个语句:

1
const foo = (params) => {} // this is not an object being returned, it's just an empty statement

因此,using语句是一个很好的开始,你可以在其中包含多行代码,如果函数旨在返回值,则需要使用"return":

1
2
3
4
const foo = (params) => {
    let value = 1;
    return value;
}

如果您想以最短的形式返回一个空对象:

1
const foo = (params) => ({})

看测试