我见过很多在 mapDispatchToProps
函数中使用 bindActionCreators
函数的示例,如下所示:
...
const mapDispatchToProps = (dispatch, props) => ({
actions: bindActionCreators({
doSomething: somethingActions.doSomething,
}, dispatch)
});
export default connect(null, mapDispatchToProps)(SomeComponent);
这意味着每次存储更改时,该组件都会更新并重新执行在 dispatch
函数中包装 somethingActions.doSomething
操作创建者,并将其作为匿名返回功能。
在构造函数中简单地执行一次这样的操作不是会更高效吗?
constructor(props) {
super(props);
const { dispatch } = props;
this.boundActionCreators = bindActionCreators({
doSomething: somethingActions.doSomething,
}, dispatch);
}
这样做有什么缺点吗?
最佳答案
mapDispatchToProps
默认情况下每个组件生命周期仅使用一次 - see this question in Redux GitHub 。它可以运行多次,理论上会导致性能问题。
可能引起麻烦的事情:
- 关注点拆分 - 将
mapDispatchToProps
作为单独的函数传递给connect()
HOC 有助于将来的重构 - 可以轻松地将连接移动到其他地方、扩展它或完全删除它 - 无需单独更改组件。 See this article from Dan Abramov about Presentational and Container Components 。在本例中,您的组件是演示组件,并且connect()
+ 它的mapDispatchToProps
是容器。 - 代码可重写性 - 构造函数可能会变得相当长且困惑 - 想象一下必须使用
boundActionCreators
10 次。 actions
的使用 - 在您的解决方案中,您需要执行this.nameOfAction()
将操作分派(dispatch)给 redux。但要获取数据,您需要执行this.props.nameOfDataProp
。采用相同的方式访问所有Redux
功能(也称为通过props
)有助于可重设计和维护。- 此外,性能提升也是值得商榷的 - 因为
mapDispatchToProps
仅在依赖于props
时才被多次使用。我鼓励您在您的应用中对此进行测试,看看是否可以获得足够好的性能提升。
TL;DR:您可以获得一些小的性能提升,但在代码维护和可重用性方面付出了很大的代价。
关于javascript - Redux - 在 React 组件的构造函数中使用 bindActionCreators 有什么缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51432050/