GoonGamja
GoonGamja

Reputation: 2286

Understanding of how to use mapDispatchToProps in react-redux?

When I make a project with react.js and react-redux usually I create an action file separately from other component files and import action-creator with connect function into a component like this way .

import { deletePost } from "../../actions"; 

connect(mapStateToProps, { deletePost })(aComponent); 

But after I found the existence of mapDispatchToProps function, it is more convenient to dispatch action to reducer from inside of a component directly.

const mapDispatchToProps = (dispatch) => {
 return {
  deletePost: (id) => { dispatch({ type: 'DELETE_POST', id: id }) }
 }
}

connect(mapStateToProps, mapDispatchToProps)(aComponent); 

Is this right way to use mapDispatchToProps function inside of a component?

Upvotes: 0

Views: 1079

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15698

Correct, that is the right way to integrate mapDispatchToProps() into your component.

Personally I find that mapDispatchToProps() makes it visible clear what your component can do. It makes it clear that your component is capable of dispatching various actions.

The typical structure is:

const mapDispatchToProps = (dispatch) => {
  return {
    nameofActionCreator: (args) => {
      dispatch(nameOfActionCreator(args))
    }
  }
}

Upvotes: 2

Related Questions