bindActionCreators 和 mapDispatchToProps - 我需要它们吗? [英] bindActionCreators and mapDispatchToProps - Do I need them?

查看:25
本文介绍了bindActionCreators 和 mapDispatchToProps - 我需要它们吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看一个 React-Redux 应用程序并尝试了解一切是如何工作的.

I'm looking at a React-Redux app and try to understand how everything is working.

在其中一个组件中,我看到了以下几行代码:

Inside one of the components, I saw these lines of code:

import { bindActionCreators } from "redux";

...

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchPhotos }, dispatch);
}

export default connect(
  null,
  mapDispatchToProps
)(SearchBar);

如果我将上面的代码更改为以下内容,一切仍然有效,没有任何错误:

If I change the above code to the following, everything still works, without any errors:

function mapStateToProps(photos) {
  return { photos };
}

export default connect(
  mapStateToProps,
  { fetchPhotos }
)(SearchBar);

对我来说,我使用connect的方式似乎更容易理解,也不需要导入额外的库.

To me, it seems that my way of using connect is easier to understand and it also doesn't need to import an extra library.

有什么理由需要导入bindActionCreators并使用ma​​pDispatchToProps?

Is there any reasons, to import bindActionCreators and use mapDispatchToProps?

推荐答案

我是 Redux 维护者.

I'm a Redux maintainer.

是的,您展示的第二个示例使用了 mapDispatch 的对象速记"形式.

Yes, the second example you showed uses the "object shorthand" form of mapDispatch.

我们建议始终使用 mapDispatch 的对象速记"形式,除非您有特定的理由来自定义调度行为.

We recommend always using the "object shorthand" form of mapDispatch, unless you have a specific reason to customize the dispatching behavior.

这篇关于bindActionCreators 和 mapDispatchToProps - 我需要它们吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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