Redux @connect装饰器中的'@'(符号)是什么? [英] What's the '@' (at symbol) in the Redux @connect decorator?

查看:700
本文介绍了Redux @connect装饰器中的'@'(符号)是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React学习Redux并偶然发现了这段代码。我不确定它是否具体是 Redux ,但我在其中一个中看到了以下代码片段示例。

I am learning Redux with React and stumbled upon this code. I am not sure if it is Redux specific or not, but I have seen the following code snippet in one of the examples.

@connect((state) => {
  return {
    key: state.a.b
  };
})

虽然功能 connect 非常简单,但在 connect 之前我不理解 @ 。如果我没有错,它甚至不是JavaScript运算符。

While the functionality of connect is pretty straightforward, but I don't understand the @ before connect. It isn't even a JavaScript operator if I am not wrong.

有人可以解释一下这是什么以及为什么使用它?

Can someone explain please what is this and why is it used?

更新:

它实际上是 react-redux ,用于将React组件连接到Redux商店。

It is in fact a part of react-redux which is used to connects a React component to a Redux store.

推荐答案

@ 符号实际上是一个JavaScript表达式目前建议用来表示装饰器

The @ symbol is in fact a JavaScript expression currently proposed to signify decorators:


装饰器可以注释和修改类和设计时的属性。

Decorators make it possible to annotate and modify classes and properties at design time.

以下是没有装饰器和装饰器设置Redux的示例:

Here's an example of setting up Redux without and with a decorator:

没有装饰者

import React from 'react';
import * as actionCreators from './actionCreators';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

function mapStateToProps(state) {
  return { todos: state.todos };
}

function mapDispatchToProps(dispatch) {
  return { actions: bindActionCreators(actionCreators, dispatch) };
}

class MyApp extends React.Component {
  // ...define your main app here
}

export default connect(mapStateToProps, mapDispatchToProps)(MyApp);

使用装饰器

import React from 'react';
import * as actionCreators from './actionCreators';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

function mapStateToProps(state) {
  return { todos: state.todos };
}

function mapDispatchToProps(dispatch) {
  return { actions: bindActionCreators(actionCreators, dispatch) };
}

@connect(mapStateToProps, mapDispatchToProps)
export default class MyApp extends React.Component {
  // ...define your main app here
}

上述两个例子都是等价的,只是一个偏好问题。此外,装饰器语法尚未构建到任何Javascript运行时中,并且仍然是实验性的并且可能会发生变化。如果您想使用它,可以使用 Babel

Both examples above are equivalent, it's just a matter of preference. Also, the decorator syntax isn't built into any Javascript runtimes yet, and is still experimental and subject to change. If you want to use it, it is available using Babel.

这篇关于Redux @connect装饰器中的'@'(符号)是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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