React-redux: this.props.dispatch is undefined if using mapDispatchToProps

Created on 15 Jan 2016  路  5Comments  路  Source: reduxjs/react-redux

Is this on purpose? I know I can bring it back myself but wouldn't it be better if it's attached all the time?

Most helpful comment

I don't think it would be better.
Usually you'd use mapDispatchToProps to hide Redux from the component you're wrapping.
Always exposing dispatch means there's no way to abstract Redux away from presentational components.

Indeed, you can bring it back yourself :-). It's just that default mapDispatchToProps is dispatch => ({ dispatch }), if you provide a custom one, it's entirely up to you what to put there.

All 5 comments

I don't think it would be better.
Usually you'd use mapDispatchToProps to hide Redux from the component you're wrapping.
Always exposing dispatch means there's no way to abstract Redux away from presentational components.

Indeed, you can bring it back yourself :-). It's just that default mapDispatchToProps is dispatch => ({ dispatch }), if you provide a custom one, it's entirely up to you what to put there.

@gaearon , I'm not sure I quite follow, how do we get dispatch passed into our component that also uses the mapDispatchToProps argument?

Thanks!

Hmm, I think I found a way:

export default connect(
(state) => {
  var productType = state.productType
  return {
    productType
  }
}, function (dispatch, props) {
  return {
    dispatch,
    ...bindActionCreators({
    ...veActions
  }, dispatch)
  }
}
)(SelectProductModalInner)

Is this the recommended way to both bind action creators to dispatch as well as get the dispatch function in your component?

Thanks!

@tnrich : yep, that looks correct. My personal opinion is that components generally shouldn't actually reference dispatch directly (per my article Why Use Action Creators? ), but if you want both dispatch and bound action creators, that's how you'd do it.

Following tnrich's answer, if I don't use spread operator, and pass dispatch as an argument like this, it still works.
function mapDispatchToProps(dispatch) { return { dispatch, someActions:bindActionCreators(someActions, dispatch) } }

Is using a spread operator mandatory here like this?
function mapDispatchToProps(dispatch) { return { dispatch, someActions: bindActionCreators({ ...someActions }, dispatch) } }

Was this page helpful?
0 / 5 - 0 ratings