react-redux: when mapDispatchToProps is object, how dispatch action works?

北战南征 提交于 2019-12-24 01:22:12

问题


During the usage of react-redux, I came across a confusing point about the mapDispatchToProps, when it is an object instead of function.

For example, in my project, I have the following action creaters:

export const incrementBy2 = () => ({
  type: INCREMENT_REQUESTED_2,
})

And in my component I import the action creator and set it up for mapDispatchToProps:

import { incrementBy2 } from '../actions'
import { connect } from 'react-redux'

// define the Home component, omit the details
const Home = props => ()

// omit the details
const mapStateToProps = state => ()

const mapDispatchToProps = {
  incrementBy2
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Home)

then in the component, I can access the action creator as props.incrementBy2, it also works well in my project.

My confusing point, incrementBy2 is just an action creator, so how and where the dispatch take place?


回答1:


According to the official docs:

[mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function): If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.

Also you can follow the source code. There you can check the implementation details.



来源:https://stackoverflow.com/questions/51257013/react-redux-when-mapdispatchtoprops-is-object-how-dispatch-action-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!