W
W
webe2018-06-24 01:19:47
React
webe, 2018-06-24 01:19:47

Why do we need bindActionCreators?

function mapDispatchToProps(dispatch) {
  return {
    getProducts: () => dispatch(getProducts()),

  };
}

Or just
{getProducts}
i.e. we stupidly throws the action creater wrapped in the dispatch into the props.
then just call this.props.getProducts(1) from our code and you're done.
but what does bindActionCreators do?
I noticed on one of the projects

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-06-24
@webe

bindActionCreators takes an object with AC as input , or a function and returns an object with AC wrapped in a call to dispatch or, in the case of a function, a function wrapped in dispatch .
If you pass an object to connect as the second argument:

const mapDispatchToProps = {
  getProducts,
};

Then your object during the connect call will be passed to the bindActionCreators call and each AC will be wrapped in a dispatch call .
This notation, in your case, is preferred, as it is shorter.
Manually wrapping AC in dispatch :
const mapDispatchToProps = (dispatch, ownProps) => ({
  getProducts: () => dispatch(getProducts()),
});

Here you can use the second argument ownProps , limit the number of arguments accepted by AC or change their order, as well as pass additional functions that do not need to be wrapped in dispatch .
Calling bindActionCreators on an object with AC :
cosnt mapDispatchToProps = dispatch => bindActionCreators(
  {
    getProducts,
  },
  dispatch,
);

There is not much point in using this recording option, since the first recording option is shorter.
But you can change it:
const mapDispatchToProps = (dispatch, ownProps) => ({
  ...bindActionCreators(
    {
      ...productsActions,
      ...usersActions,
      ...ordersActions,
    },
    dispatch,
  ),
  () => getSomeOther(ownProps.someProp),
  notNeedsToWrapInDispatch,
})

In this form, you can pass many ACs to bindActionCreators as is, and separately pass additional ACs wrapped in dispatch , which will use ownProps or functions that do not need to be wrapped in dispatch .

A
Alexander, 2018-06-24
@atcrew

Docks (eng)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question