我觉得没有一个答案明确说明为什么mapDispatchToProps 有用。
这真的只能在container-component 模式的上下文中回答,我发现首先阅读:Container Components 然后Usage with React 最能理解。
简而言之,您的components 应该只关心显示内容。 他们应该从中获取信息的唯一地方是他们的道具。
与“显示的东西”(组件)分开的是:
这就是containers 的用途。
因此,模式中的“精心设计”component 如下所示:
class FancyAlerter extends Component {
sendAlert = () => {
this.props.sendTheAlert()
}
render() {
<div>
<h1>Today's Fancy Alert is {this.props.fancyInfo}</h1>
<Button onClick={sendAlert}/>
</div>
}
}
看看这个组件如何从 props 获取它显示的信息(通过 mapStateToProps 来自 redux 存储),它还从它的 props 获取它的操作函数:sendTheAlert()。
这就是mapDispatchToProps 出现的地方:在相应的container中
// FancyButtonContainer.js
function mapDispatchToProps(dispatch) {
return({
sendTheAlert: () => {dispatch(ALERT_ACTION)}
})
}
function mapStateToProps(state) {
return({fancyInfo: "Fancy this:" + state.currentFunnyString})
}
export const FancyButtonContainer = connect(
mapStateToProps, mapDispatchToProps)(
FancyAlerter
)
我想知道你是否能看到,现在是 container 1 知道 redux 和 dispatch 以及 store 和 state 等等。
模式中的component,FancyAlerter,它不需要知道任何这些东西:它通过它的道具获取它的方法来调用按钮的onClick。
而且 ...mapDispatchToProps 是 redux 提供的有用方法,可以让容器轻松将该函数传递到其 props 上的包装组件中。
所有这些看起来很像文档中的待办事项示例,以及此处的另一个答案,但我尝试根据模式对其进行投射以强调为什么。
(注意:您不能将mapStateToProps 用于与mapDispatchToProps 相同的目的,因为您无法在mapStateToProp 中访问dispatch。所以您不能使用@987654347 @ 给被包装的组件一个使用dispatch的方法。
我不知道他们为什么选择将它分成两个映射函数 - 让 mapToProps(state, dispatch, props) IE 一个函数同时完成这两个函数可能会更整洁!
1 请注意,我故意将容器明确命名为FancyButtonContainer,以强调它是一个“事物”——作为“事物”的容器的身份(因此存在!)有时会丢失简而言之
export default connect(...)
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
大多数示例中显示的语法