没有花括号的箭头功能

没有花括号的箭头功能

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

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

const handleBar = (e) => {
    e.preventDefault();
    dispatch('logout');};

谢谢你的帮助!


长风秋雁
浏览 394回答 3
3回答

跃然一笑

括号返回单个值,花括号执行多行代码。您的示例看起来很混乱,因为它使用的JSX看起来像多个“行”,但实际上只是编译为单个“元素”。以下是一些例子,它们都做同样的事情:const a = (who) => "hello " + who + "!";const b = (who) => (&nbsp; &nbsp; "hello " +&nbsp;&nbsp; &nbsp; who +&nbsp;&nbsp; &nbsp; "!");const c = (who) => {&nbsp; return "hello " + who + "!";};&nbsp;您还经常会看到围绕对象文字的括号,因为这是一种避免解析器将其视为代码块的方法:const x = () => {} // Does nothingconst y = () => ({}) // returns an object

神不在的星期二

也可以使用花括号来防止单行箭头函数返回一个值 - 或者让下一个开发人员明白单行箭头函数不应该返回任何东西。例如:const myFunc = (stuff) => { someArray.push(stuff) }const otherFunc = (stuff) => someArray.push(stuff)console.log(myFunc())&nbsp; &nbsp; // --> logs undefinedconsole.log(otherFunc()) // --> logs result of push which is new array length

ibeautiful

实际上在公文包中有人在箭头函数声明中使用大括号时,它等于下面:const arrow = number => number + 1;|||const arrow = (number) => number + 1;|||&nbsp; &nbsp;&nbsp;const arrow = (number) => ( number + 1 );|||const arrow = (number) => { return number + 1 };
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript