3 回答

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

TA贡献1963条经验 获得超6个赞
也可以使用花括号来防止单行箭头函数返回一个值 - 或者让下一个开发人员明白单行箭头函数不应该返回任何东西。
例如:
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

TA贡献1993条经验 获得超5个赞
实际上在公文包中有人在箭头函数声明中使用大括号时,它等于下面:
const arrow = number => number + 1;
|||
const arrow = (number) => number + 1;
|||
const arrow = (number) => ( number + 1 );
|||
const arrow = (number) => { return number + 1 };
添加回答
举报