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

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

问题描述

我正在用 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 的一部分,用于连接一个将组件反应到 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 装饰器中的“@"(at 符号)是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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