问题描述
function mapStateToProps(state) {
return { todos: state.todos }
}
function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(actionCreators, dispatch) }
}
export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
为什么我会使用 mapDispatchToProps 和 bindActionCreators 作为第二个道具
why would i use mapDispatchToProps and bindActionCreators as second prop if
export default connect(mapStateToProps, { getSthAction })(TodoApp)
这样也能用吗?有什么区别吗?
this way it works as well? is there any difference?
推荐答案
这些示例中唯一的区别是您的 mapDispatch
函数将导致 this.props.actions.someAction()
,而不是 this.props.someAction()
,因为您将 bindActionCreators
的结果显式返回为名为 actions
的字段>.
The only difference in those examples is that your mapDispatch
function will result in this.props.actions.someAction()
, rather than this.props.someAction()
, because you're explicitly returning the result of bindActionCreators
as a field called actions
.
我个人推荐总是使用对象速记"版本 - 对我来说,从来没有真正编写单独的 mapDispatch
功能.
I personally recommend always using the "object shorthand" version - to me, there's never a good reason to actually write a separate mapDispatch
function.
这篇关于为什么使用 bindActionCreator 而不是传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!