Reputation: 334
I'm developing a universal react application using redux. in my action creators I dispatch my data to store.
in ComponentDidMount function dispatch function is Ok but when I want pass it to component in render function It gives me error that Cannot read property 'dispatch' of undefined How I can pass my dispatch functions to component?
Container Code :
class DealContainer extends React.Component {
static readyOnActions(dispatch, params) {
return Promise.all([
dispatch(DealsActions.fetchDealData(params.id)),
dispatch(SubmitActions.fetchSubmitInitialData()),
]);
}
componentDidMount() {
DealContainer.readyOnActions(this.props.dispatch,this.props.params);
}
render() {
return(
<MyComponent
changeStoreFunction = {this.props.dispatch(SubmitActions.changeUserId)}
/>)
}
const mapStateToProps = (state, ownProps) => {
return {
dealData: state.dealData,
routing: ownProps.location.query,
submitInitialData: state.submitInitialData,
id: ownProps.params.id,
mapInfo: state.mapInfo,
areaList: state.areaList,
}
};
DealContainer.propTypes = {
params: PropTypes.shape({
id: PropTypes.string.isRequired,
}).isRequired,
dispatch: PropTypes.func.isRequired,
};
}
export default connect(mapStateToProps)(DealContainer);
Upvotes: 1
Views: 2531
Reputation: 1212
Indeed, you need to use mapDispatchToProps to get access to the dispatch function.
There you can define your function that will be called within your component render method :
const mapDispatchToProps = (dispatch) => {
return {
yourFunctionToCallFromComponent: () => {
dispatch(yourAction())
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DealContainer);
Upvotes: 1