236

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

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

虽然 的功能connect非常简单,但我不明白@之前的connect. 如果我没记错的话,它甚至不是 JavaScript 运算符。

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

更新:

它实际上react-redux是用于将 React 组件连接到 Redux 存储的一部分。

4

2 回答 2

384

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

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

下面是一个使用装饰器和不使用装饰器设置 Redux 的示例:

没有装饰器

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

于 2015-09-20T04:56:50.433 回答
52

很重要!

这些道具称为状态道具,它们与普通道具不同,对组件状态道具的任何更改都会一次又一次地触发组件渲染方法,即使您不使用这些道具,因此出于性能原因尝试仅绑定到您的组件您在组件中需要的状态道具,如果您使用子道具,则仅绑定这些道具。

示例:假设在您的组件内部您只需要两个道具:

  1. 最后一条消息
  2. 用户名

不要这样做

@connect(state => ({ 
   user: state.user,
   messages: state.messages
}))

做这个

@connect(state => ({ 
   user_name: state.user.name,
   last_message: state.messages[state.messages.length-1]
}))
于 2017-04-09T16:53:14.360 回答