Reputation: 2909
I want to have multiple actionCreators dispatched into one component. I know you can do this with state
export default connect(
(state: ApplicationState) => Object.assign({}, state.search, state.resources),
ResourcesState.actionCreators// i have another actionCreator I want to add
)(Home) as typeof Home;
But not sure the syntax to do this with actionCreators. I have read into
mapDispatchToProps
But not sure how to implement.
Upvotes: 1
Views: 1612
Reputation: 1443
The second argument to connect takes an object, so you can use of ES6 syntax and avoid the use of mapDispatchToProps
.
import { yourAction } from './your_actions_folder'
class Home extends Component{
....
//For dispatch a action you only call the action Creator
this.props.yourAction()
}
export default connect(mapStateToProps,{yourAction})(Home)
Upvotes: 0
Reputation: 67627
There are a few ways to set up dispatching of Redux actions in React components:
connect(mapState)(MyComponent)
. By default, your component will be given props.dispatch
, and you can call props.dispatch({type : "SOME_ACTION"})
.Pass a mapDispatchToProps
function as the second argument to connect. Inside, you can create new function references that call dispatch
:
function mapDispatchToProps(dispatch) {
return {
addTodo : (text) => dispatch({type : "ADD_TODO", text})
}
}
You can also use the Redux bindActionCreators
utility instead:
function mapDispatchToProps(dispatch) {
return bindActionCreators({addTodo, toggleTodo}, dispatch);
}
Finally, you can pass an object full of action creators directly to connect
:
const actions = {addTodo, toggleTodo};
export default connect(mapState, actions)(MyComponent);
I highly recommend the fourth approach, which I also talk about in my blog post Idiomatic Redux: Why Use Action Creators?.
Upvotes: 2
Reputation: 282160
the Second argument to connect takes an object
or a functio
n so you can add
export default connect(
(state: ApplicationState) => Object.assign({}, state.search, state.resources),
{
ResourcesState.actionCreators,
some_other_action_creators,
some_more
}
)(Home) as typeof Home;
Also read through this answer on Stackoverflow for more information on how to use action creators
Why is there no need for a mapDispatchToProps function here?
Upvotes: 0
Reputation: 7424
mapDispatchToProps
is the second argument in connect
. So for example:
import customAction from 'actions-directory-in-your-app'
const mapStateToProps = () => {} // no implementing anything for example purposes
const mapDispatchToProps = () => ({ customAction })
const ConnectedContainer = connect(
mapStateToProps,
mapDispatchToProps
)(YourContainer)
customAction
becomes now a prop in YourContainer
so you can use it the same way other props within your component.
Upvotes: 0