简体   繁体   English

React - 箭头 function 语法

[英]React - arrow function syntax

Long story short when working in React, there are situations when I have to use arrow functions with () instead of {} and vice-versa.长话短说,在 React 中工作时,在某些情况下我必须使用带有()而不是{}的箭头函数,反之亦然。

const foo = (item) => ( ... );

and

const foo = (item) => { ... };

My code is often failing because I am confusing them.我的代码经常失败,因为我混淆了它们。 What, I am trying to understand is the difference between the two arrow functions.我想了解的是两个箭头函数之间的区别。 What are the best-case scenarios for both?两者的最佳情况是什么?

Many thanks!非常感谢!

Arrow function without curly braces return the function expression.没有大括号的箭头 function 返回 function 表达式。 Example:例子:

() => 'Hello world';

will do the same as会做同样的事情

function() {
  return 'Hello world';
}

If you use curly braces, you can add multiple statements.如果使用花括号,则可以添加多个语句。 Example:例子:

() => {
  const str = 'Hello world';
  return str;
}

will do the same as:将做同样的事情:

function() {
  const str = 'Hello world';
  return str;
}

See the MDN docs for more details.有关更多详细信息,请参阅MDN 文档

Some little extra notes:一些额外的注意事项:

Because of the syntax rules, when you want to return an object in an arrow function, you'll have to wrap it in braces:由于语法规则,当您想在箭头 function 中返回 object 时,您必须将其包裹在大括号中:

() => ({
  key: 'value',
  another_key: 'another_value'
});

The main differences between function() and () =>... are that arrow functions don't have bindings to some keywords (like this ) and that arrow functions don't have a prototype and can't be used as constructors. function()() =>...之间的主要区别在于箭头函数没有绑定到某些关键字(如this ),并且箭头函数没有原型并且不能用作构造函数。

Not sure whether I understand you correctly, but:不确定我是否理解正确,但是:

const oneLiner = (param) => myArr.filter().map();

const twoLiner = (param) => {func1(); func2();}

If you can put everything in one line (like mapping or filtering) you dont need any parentheses for the body of your function.如果您可以将所有内容放在一行中(例如映射或过滤),则 function 的正文不需要任何括号。 If you need more than one line, use {}.如果您需要多行,请使用 {}。

Also, the oneLiner returns a value, even without "return".此外,即使没有“返回”, oneLiner 也会返回一个值。 The second function does need the keyword "return" to return something.第二个 function 确实需要关键字“return”来返回一些东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM