Javascript Redux-在React组件的构造函数中使用BindActionCreator有什么缺点吗?
我在Javascript Redux-在React组件的构造函数中使用BindActionCreator有什么缺点吗?,javascript,reactjs,redux,Javascript,Reactjs,Redux,我在mapDispatchToProps函数中看到了许多使用bindActionCreators函数的示例,如下所示: ... const mapDispatchToProps = (dispatch, props) => ({ actions: bindActionCreators({ doSomething: somethingActions.doSomething, }, dispatch) }); export default connect(nu
mapDispatchToProps
函数中看到了许多使用bindActionCreators
函数的示例,如下所示:
...
const mapDispatchToProps = (dispatch, props) => ({
actions: bindActionCreators({
doSomething: somethingActions.doSomething,
}, dispatch)
});
export default connect(null, mapDispatchToProps)(SomeComponent);
这意味着每次存储更改时,此组件将更新并重新执行在dispatch
函数中包装somethingActions.doSomething
action creator并将其作为匿名函数返回
在构造函数中这样简单地执行一次不是更有效吗
constructor(props) {
super(props);
const { dispatch } = props;
this.boundActionCreators = bindActionCreators({
doSomething: somethingActions.doSomething,
}, dispatch);
}
这样做有什么缺点吗?
mapDispatchToProps
默认为每个组件生命周期只使用一次。它可以运行多次,理论上会导致性能问题
可能引起麻烦的事情:
- 关注点的分离-将
作为单独的函数传递给mapDispatchToProps
HOC有助于将来的重构-可以轻松地将连接移动到其他任何位置,扩展或完全删除它,而无需单独更改组件。在本例中,您的组件是表示性的,connect()
+它是connect()
容器mapDispatchToProps
- 代码可重用性-构造函数可能变得相当长和混乱-想象一下必须使用
boundActionCreators
10次 - 使用
-对于您的解决方案,您需要执行操作
将操作分派到redux。但对于获取数据,您可以执行this.nameOfAction()
。以同样的方式访问所有this.props.nameOfDataProp
功能(即通过Redux
)有助于可再开发性和维护props
- 此外,性能提升也是可以讨论的-因为只有当它依赖于
道具时,
才会被多次使用。我鼓励您在应用程序中测试这一点,看看您是否能够获得足够好的性能提升mapDispatchToProps
TL;DR:您可以获得一些小的性能提升,但在代码维护和可重用性方面要付出很大的代价。是的
mapDispatch
在组件创建时运行一次,除非使用ownProps
参数。我的建议是使用“对象速记”并将一个充满动作创建者的对象传递给connect
,这样可以缩短时间。你能举一个你提到的“对象速记”的例子吗?