Why use bindActionCreator instead of passing an ob

2019-06-01 10:11发布

问题:

function mapStateToProps(state) {
 return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
 return { actions: bindActionCreators(actionCreators, dispatch) }
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)

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?

回答1:

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.

I personally recommend always using the "object shorthand" version - to me, there's never a good reason to actually write a separate mapDispatch function.