我觉得没有一个答案能够阐明为什么mapDispatchToProps很有用。
这个问题只有在容器组件-展示组件模式的背景下才能回答,最好先阅读 容器组件 然后是与React一起使用。
简而言之,你的组件只应该关心展示内容, 唯一从哪里获取信息的地方是它们的props。
与“显示内容”(组件)分开的是:
这就是容器的作用。
因此,在该模式下,“设计良好”的组件应该像这样:
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 store 中获取),并从其 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
)
我想知道你是否能够看到,现在它是container1知道redux,dispatch,store和state等内容。
模式中的FancyAlerter组件负责渲染,不需要了解这些内容:它通过props获得调用方法,用于按钮的onClick事件。
而mapDispatchToProps是redux提供的有用手段,让容器可以轻松地将该函数传递到包装的组件上的props中。
所有这些看起来都很像文档中的todo示例和另一个答案,但我试图从模式的角度解释它,以强调为什么要这样做。
(请注意:mapStateToProps不能用于与mapDispatchToProps相同的目的,其基本原因是您无法在mapStateToProps内部访问dispatch。因此,您不能使用mapStateToProps为包装的组件提供使用dispatch的方法。)
我不知道为什么他们选择将其分成两个映射函数 - 可能更整洁的方法是mapToProps(state, dispatch, props),即一个函数同时完成两个功能!
1请注意,我故意明确地将容器命名为FancyButtonContainer,以突出它是一个“东西” - 容器的身份(因此也存在!)有时会在缩写中丢失
export default connect(...)
这是大多数示例中显示的语法缩写
ALERT_ACTION到底是指代操作函数还是从操作函数返回的type类型?:/ 感到很困惑。 - Jamie Hutber