which version of mapDispatchToProps should be used?


(Defrian) #1

hi guys,

I am a little confused about redux mapDispatchToProps. I found 3 versions while checking the web. are they all equal or should I prefer one over another?

# VERSION 1 #
-------------
import { changeBaseCurrency } from '../actions/currencies';
...
this.props.dispatch(changeBaseCurrency(currency));
...
export default connect(mapStateToProps)(CurrencyList);


# VERSION 2 #
-------------
import { changeBaseCurrency } from '../actions/currencies';
...
this.props.changeBaseCurrency(currency);
...
export default connect(mapStateToProps, { changeBaseCurrency })(CurrencyList);


# VERSION 3 #
-------------
import { changeBaseCurrency } from '../actions'
...
changeCurrencies(amount);
...
const mapDispatchToProps = dispatch => {
  return {
    changeCurrencies: amount => {
      dispatch(changeBaseCurrency(amount))
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(CurrencyList);

(Joe Dodd) #2

Not to muddy the waters too much more, but I’ve used a fourth option like so…

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../redux/actions';

/* --- */

const { myAction } = this.props.actions;
myAction(args);

/* --- */

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

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

To each their own, though.