且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

没有花括号的箭头函数

更新时间:2022-12-29 09:24:08

括号返回单个值,大括号执行多行代码.

The parenthesis are returning a single value, the curly braces are executing multiple lines of code.

您的示例看起来令人困惑,因为它使用的是 JSX,看起来像多行";但实际上只是被编译为单个元素".

Your example looks confusing because it's using JSX which looks like multiple "lines" but really just gets compiled to a single "element."

这里有更多的例子,它们都做同样的事情:

Here are some more examples that all do the same thing:

const a = (who) => "hello " + who + "!";
const b = (who) => ("hello " + who + "!");
const c = (who) => (
  "hello " + who + "!"
);
const d = (who) => (
  "hello "
    + who
    + "!"
);
const e = (who) => {
  return "hello " + who + "!";
}; 

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

You will also often see parenthesis around object literals because that's a way to avoid the parser treating it as a code block:

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