没有花括号的箭头功能

dki*_*mot 47 javascript ecmascript-6 react-jsx arrow-functions

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

const foo = (params) => (
    <span>
        <p>Content</p>
    </span>
);
Run Code Online (Sandbox Code Playgroud)

const handleBar = (e) => {
    e.preventDefault();
    dispatch('logout');
};
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

dav*_*vid 92

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

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

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

const a = (who) => "hello " + who + "!";
const b = (who) => (
    "hello " + 
    who + 
    "!"
);
const c = (who) => {
  return "hello " + who + "!";
}; 
Run Code Online (Sandbox Code Playgroud)

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

const x = () => {} // Does nothing
const y = () => ({}) // returns an object
Run Code Online (Sandbox Code Playgroud)

  • 太棒了,谢谢你。这也有助于我理解我遇到的其他一些错误。一旦我可以,我会接受它是正确的。谢谢大卫 (2认同)
  • 也可以使用花括号防止箭头函数返回值-或很明显,单行箭头函数不应返回任何值。查看我的答案以获取示例(无法很好地将其格式化为注释)。 (2认同)
  • 我有GrayedFox的主意,但是,为什么有人甚至实现了这一点?对我来说似乎有点棘手,因为在特殊情况下,您不确定是()还是{} (2认同)

Gra*_*Fox 16

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

例如:

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
Run Code Online (Sandbox Code Playgroud)


小智 10

括号有一个隐式返回语句,而大括号则需要一个显式返回语句


Abh*_*mar 8

括号在箭头函数中用于返回一个对象。

() => ({ name: 'YourName' })  // This will return an object
Run Code Online (Sandbox Code Playgroud)

那相当于

() => {
   return { name : 'YourName' }
}
Run Code Online (Sandbox Code Playgroud)


Ame*_*icA 6

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

const arrow = number => number + 1;

|||

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

|||    

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

|||

const arrow = (number) => { return number + 1 };
Run Code Online (Sandbox Code Playgroud)


小智 6

如果在箭头后面使用大括号来定义函数体,则必须使用“return”关键字来返回某些内容。

例如:

const myFun1 = (x) => {
    return x;
}; // It will return x

const myFun2 = (x) => {
    x;
}; // It will return nothing
Run Code Online (Sandbox Code Playgroud)

如果使用括号,则无需提及“return”关键字。

例如:

const myFunc1 = (x) => x; // It will return x

const myFunc2 = (x) => (x); // It will also return x
Run Code Online (Sandbox Code Playgroud)