In one of Dan Abramov's answers, there is code
// action creator
function loadData(dispatch, userId) { // needs to dispatch, so it is first argument
return fetch(`http://data.com/${userId}`)
.then(res => res.json())
.then(
data => dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
err => dispatch({ type: 'LOAD_DATA_FAILURE', err })
);
}
// component
componentWillMount() {
loadData(this.props.dispatch, this.props.userId); // don't forget to pass dispatch
}
It seems the mapDispatchToProps
just maps a generic dispatch as props (as this.props.dispatch
), so this component can dispatch any action at all?
First, is it a good form, or is it just an example but we should make it specific dispatch, such as this.props.dataReceived
?
Second, so it looks like for the above code, the mapDispatchToProps
would be written as:
const mapDispatchToProps = dispatchOfReduxStore => {
return {
dispatch: dispatchOfReduxStore
}
}
or even just:
const mapDispatchToProps = dispatch => {
return {
dispatch
}
}
and simplified to:
const mapDispatchToProps = dispatch => ({ dispatch })
and this.props.dispatch
becomes a versatile dispatch?
I also found that when we simply omit the mapDispatchToProps
in connect()
, then this.props.dispatch
is automatically available.