我正在学习Redux with React,偶然发现了这段代码。我不确定它是否是特定于Redux的,但我在其中一个示例中看到了以下代码片段。
@connect((state) => {
return {
key: state.a.b
};
})
虽然connect
的功能非常简单,但我不理解connect
之前的@
。如果我没记错的话,它甚至不是JavaScript运算符。
有人能解释一下这是什么吗?为什么要用它?
更新:
它实际上是react-redux
的一部分,用于将React组件连接到Redux存储。
发布于 2015-09-20 12:56:50
@
符号实际上是一个JavaScript表达式currently proposed to signify
装饰器使得在设计时注释和修改类和属性成为可能。
下面是在没有装饰器的情况下和使用装饰器的情况下设置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。
发布于 2017-04-10 00:53:14
非常重要!
这些道具被称为状态道具,它们与普通道具不同,组件状态道具的任何更改都会一次又一次地触发组件呈现方法,即使您不使用这些道具,因此出于性能的原因,尝试仅绑定组件中所需的状态道具,如果您使用子道具,则仅绑定这些道具。
例如:假设在你的组件中,你只需要两个道具:
user name的最后一条消息
,不这样做
@connect(state => ({
user: state.user,
messages: state.messages
}))
执行此操作
@connect(state => ({
user_name: state.user.name,
last_message: state.messages[state.messages.length-1]
}))
https://stackoverflow.com/questions/32646920
复制相似问题