箭头与a()之间的功能是什么? [英] What does the arrow function with a () after means?

查看:206
本文介绍了箭头与a()之间的功能是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const actionsMap = {
  [GET_USER]: (state, action) => ({ post: action.msg })
};

我有这个我偶然发现的代码。我一直在使用{}格式的箭头函数,这个()包装是什么意思?

I have this code that I've stumbled upon. All the time I've been working with arrow functions I've seen on a {} format, what does this () wrapper mean?

推荐答案

使用箭头函数,您可以使用单个语句或块作为函数体。这两个是等价的:

With arrow functions, you can either use a single statement or a block as the function body. These two are equivalent:

() => foo
() => {
  return foo;
}

在你的例子中,如果lambda被定义为 ()=> {post:action.msg} 对象( {} )将被解释为一个body块而不是一个对象。运行时将尝试将其解析为等价于:

In your example, if the lambda was defined as () => {post: action.msg} the object ({}) would be interpreted as a body block instead of an object. The runtime would try to parse it as an equivalent to:

function () {
  post: action.msg
}

这是一个命名的标签和属性访问,在这里没有什么意义。通过包含在括号中,您提示解析器它是一个要被评估的表达式,并且单个表达体上的胖箭头函数规则踢入,使其相当于:

which is a named label and property access, and doesn't make much sense here. By wrapping in parens, you hint to the parser that it is an expression to be evaluated and the fat arrow function rules on single-expression bodies kick in, making it equivalent to:

function () {
  return {post: action.msg};
}

想要执行两个相关的事情时,要解决单一表达规则(偶尔在map / reduce算法中很有用),您可以使用括号对一对表达式进行分组:

To work around the single-expression rules when you want to do two related things (occasionally useful in map/reduce algorithms), you can use parens to group a pair of expressions:

foo.reduce((p, c) => (c.counted = true, p += c.value));

这将设置计数 code> c ,然后将 c.value 添加到 p 并返回 p + = c.value 的结果作为新值 p

This will set the counted property of c, before adding c.value to p and returning the result of p += c.value as the new value of p.

圆括号中包含ECMAScript中的一个表达式,可以使用逗号运算符对多个表达式进行分组。

The parentheses wrap an expression in ECMAScript and can be used, with the comma operator, to group multiple expressions. The results of the last expression are returned when the group is evaluated.

例如:

var i = 0, j = 0;
console.log((j += 10, i += 2), j);

将打印 2 10 ,因为 j ()组中增加,稍后打印。

will print 2 10, since j is incremented in the () group and printed later.

这篇关于箭头与a()之间的功能是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆