es6中的装饰器如何工作? [英] How do decorators in es6 work?

查看:85
本文介绍了es6中的装饰器如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习redux,发现文档中的示例在此签名中使用 connect

I'm learning redux and see that the examples in the doc use connect in this signature:

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

但是在其他回购中的其他地方,我也看到了这一点-

But in other places from other repos I've also seen this-

@connect(mapStateToProps, mapDispatchToProps)

我得到了同样的东西,但是如何签名装饰工?看起来好像没有在connect的结果中设置变量,所以 @connect 的功能在哪里分配?

I get that there the same thing but how does the signature of a decorator work? It doesn't look like it's setting a variable to the result of the connect so where does the function of @connect go to and get assigned to?

推荐答案

装饰器只是用于处理他们看到的 next 事物的高阶函数。

Decorators are just higher-order functions that work on the next thing that they see.

这是一种作弊(不是真的),但是如果我们将其简化为您可以考虑仅使用简单值的格式:

This is sort of cheating (not really sort of, it is), but if we simplified this to a format that you could reason about using just simple values:

const add = x => y => x + y;

添加的函数期望 x ,并返回期望 y

的函数,然后返回 x + y

您可以这样称呼

Add is a function that expects an x, and returns a function that expects a y,
and then returns x + y;
You can call it like

add(1)(2); // 3

const add1 = add(1);
add1(2); // 3

但是如果我们有某种方法告诉JS不要期望最后一次通过值,而是直接对所看到的下一个东西运行它。

But what if we had some way of telling JS not to expect to pass in the last value, but instead just run what it has on the next thing it sees.

@add(1)
2; // 3

@add1
2; // 3

就像我说的那样,这个示例实际上不是这样工作的(在那种装饰器中函数实际上并不是要加上两个数字,就像修改类,方法或参数一样),但这是装饰器背后的基本概念。

Like I said, this example doesn't really work this way (in that a decorator function wouldn't really be meant for adding two numbers, so much as modifying classes or methods or parameters), but that is the basic concept behind the decorators.

@connect(mapProps, mapHandlers)
MyComponent;

就是说

connect(mapProps, mapHandlers)(MyComponent);

这篇关于es6中的装饰器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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