react-redux:当 mapDispatchToProps 是对象时,调度操作如何工作?
在使用 react-redux
的过程中,我遇到了一个关于 mapDispatchToProps
的困惑点,当它是一个对象而不是函数时.
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,
})
在我的组件中,我导入了 action creator 并为 mapDispatchToProps 设置了它:
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)
然后在组件中,我可以通过 props.incrementBy2
访问动作创建者,它在我的项目中也运行良好.
then in the component, I can access the action creator as props.incrementBy2
, it also works well in my project.
我的困惑点,incrementBy2
只是一个动作创建者,那么如何以及在哪里进行分派?
My confusing point, incrementBy2
is just an action creator, so how and where the dispatch take place?
根据 官方文档:
[mapDispatchToProps(dispatch, [ownProps]): dispatchProps](对象或函数):如果传递了一个对象,则假定其中的每个函数都是 Redux 动作创建者.具有相同函数名称但每个动作创建者都包含在调度调用中以便可以直接调用它们的对象将合并到组件的 props 中.
[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.