React Redux mapDispatchToProps 与 this.props.dispatch [英] React Redux mapDispatchToProps vs this.props.dispatch
问题描述
直到现在,我都是这样使用容器和组件操作的:
Until now I used my containers and components actions this way:
<Header btnMnuAction={this.props.toggleSidebar} logout={this.props.logout}/>
使用 mapDispatchToProps 函数:
With the mapDispatchToProps function:
const mapDispatchToProps = (dispatch) => {
return {
toggleSidebar: () => {
dispatch(toggleSidebar());
},
logout: () => {
dispatch(logout());
}
}
};
现在我是这样试的:
<Header btnMnuAction={() => this.props.dispatch(toggleSidebar())} logout={() => this.props.dispatch(logout())} >
请问,有人可以向我解释这些选项之间的区别吗?
Please, can someone explain to me what's the difference between these options?
谢谢:)
推荐答案
mapDispatchToProps
的基本作用正是您在示例中内联的作用,但是,它更灵活,因为它可以接受不只有调度程序,但目标组件的状态和自己的道具.
The base role of mapDispatchToProps
is exactly what you do inline in your example, however, it is more flexible as it can accept not only the dispatcher but the target component's state and own props.
你可以使用这些额外的参数来改变基于组件状态的行为(例如,如果它是 disabled
那么你可以不返回绑定动作)或道具(例如,如果有 cleanStorage
在组件自己的 props 中,将其与 logout
操作一起传递).
You can use these extra parameters to change behavior based on component state (for example if it is disabled
then you may return no bound actions) or props (for example, if there is cleanStorage
in own props of the component, pass it along the logout
action).
使用 mapDispatchToProps
使您的代码更清晰,更好地分离.想象一下传递 10 多个动作并手动绑定它们......消费者组件应该只接受定义的动作,而不是通用的dispatch
,这样,它减少了与 Redux 的耦合,并允许更容易的维护和测试.
Using mapDispatchToProps
makes your code cleaner and better separated. Imagine passing 10+ actions and binding them manually... Consumer components should only accept defined actions, not a generic dispatch
and by that, it reduces coupling to the Redux and allows for easier maintenance and testing.
通过使用一些高级功能,您可以定义更简单的函数bind
,您只需将调度函数绑定到动作创建者,例如:
By using some advanced features you can define simpler function bind
, where you just bind the dispatch function to the action creators, for example like this:
const bind => actions => dispatch =>
Object.entries(actions)
.map(([key, action]) => [key, (...args) => dispatch(action(...args)])
.reduce((acc, ([key, boundAction]) => ({...acc, [key]: boundAction}), {})
connect(mapStateToProps, bind( { toggleSidebar, logout } ), ...)(Component)
或者只是使用 bindActionCreators(actionCreators, dispatch)减少样板:
Or just use bindActionCreators(actionCreators, dispatch) to reduce boilerplate:
import { bindActionCreators } from 'redux';
connect(
mapStateToProps,
dispatch => bindActionCreators( { toggleSidebar, logout }, dispatch),
...
)(Component)
这篇关于React Redux mapDispatchToProps 与 this.props.dispatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!