是的,这是正确的。它只是一个帮助程序函数,可以更简单地访问状态属性
想象一下您posts
的应用程序中有一把钥匙state.posts
state.posts //
/*
{
currentPostId: "",
isFetching: false,
allPosts: {}
}
*/
和组件 Posts
默认情况下connect()(Posts)
将使所有状态道具可用于连接的组件
const Posts = ({posts}) => (
<div>
{/* access posts.isFetching, access posts.allPosts */}
</div>
)
现在,当您将映射state.posts
到您的组件时,它会变得更好
const Posts = ({isFetching, allPosts}) => (
<div>
{/* access isFetching, allPosts directly */}
</div>
)
connect(
state => state.posts
)(Posts)
mapDispatchToProps
通常你必须写 dispatch(anActionCreator())
和bindActionCreators
你一起也可以更轻松地做到
connect(
state => state.posts,
dispatch => bindActionCreators({fetchPosts, deletePost}, dispatch)
)(Posts)
现在您可以在组件中使用它
const Posts = ({isFetching, allPosts, fetchPosts, deletePost }) => (
<div>
<button onClick={() => fetchPosts()} />Fetch posts</button>
{/* access isFetching, allPosts directly */}
</div>
)
更新actionCreators。
一个actionCreator的示例: deletePost
const deletePostAction = (id) => ({
action: 'DELETE_POST',
payload: { id },
})
因此,bindActionCreators
只需执行您的操作,然后将其包装即可dispatch
。(我没有阅读redux的源代码,但是实现可能看起来像这样:
const bindActionCreators = (actions, dispatch) => {
return Object.keys(actions).reduce(actionsMap, actionNameInProps => {
actionsMap[actionNameInProps] = (...args) => dispatch(actions[actionNameInProps].call(null, ...args))
return actionsMap;
}, {})
}