javascript 函数中 () 和 {} 有什么区别?

chr*_*358 8 javascript reactjs

这些函数似乎在 React 教程中可以互换使用,但无法弄清楚其中的区别......或者何时使用哪个?

const SomeVal = () => {
    ...
}

const SomeVal = () => (
    ...
)
Run Code Online (Sandbox Code Playgroud)

Li3*_*357 8

这些是根本不同的。以前的箭头函数语法() => {}允许您在箭头函数体内有多个语句,即:

() => {
  console.log('Hello!');
  return 'World!';
}
// When called, this logs Hello! and returns World!
Run Code Online (Sandbox Code Playgroud)

但后者() => ()是一个箭头函数,它隐式返回一个用括号括起来的表达式(称为分组运算符)。它没有明确允许多个语句:

() => (
  'World' // only one expression that is implicitly returned
  // Would work fine without parentheses (unless you want to return an object!)
)
// When called, this function returns 'World'
Run Code Online (Sandbox Code Playgroud)

当然,您也可以创建一个不可读的箭头函数,使用逗号运算符执行多个操作:

() => (console.log('Hello!'), 'World!')
Run Code Online (Sandbox Code Playgroud)

反应

我假设您在 React 无状态组件中看到了这一点:

const Comp = () => (
  <div>Hello World!</div>
);
Run Code Online (Sandbox Code Playgroud)

该函数(组件只是函数)<div>隐式返回元素。但是,使用{},您可以进行一些中间计算,而不是立即返回:

const Comp = () => {
  const msg = 'Hello World!';
  return ( // Need to explicitly return here
    <div>{msg}</div>
  );
}
Run Code Online (Sandbox Code Playgroud)