Javascript bindActionCreators调用了一个调度
我的印象是,Javascript bindActionCreators调用了一个调度,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,我的印象是,bindActionCreators的目的是将actionCreators包装在分派函数中,并为这些新函数命名(可以通过mapDispatchToProps和connect作为道具传递给组件) 然而,我发现的一个教程似乎在调度函数(updatePerson)上调用了bindActionCreators),这似乎违反了bindActionCreators的全部要点 操作/更新_person.js 组件/WantedCard.js 以我的理解,我到底做错了什么?UpdatePerson已
bindActionCreators
的目的是将actionCreators
包装在分派函数中,并为这些新函数命名(可以通过mapDispatchToProps
和connect
作为道具传递给组件)
然而,我发现的一个教程似乎在调度函数(updatePerson
)上调用了bindActionCreators
),这似乎违反了bindActionCreators
的全部要点
操作/更新_person.js
组件/WantedCard.js
以我的理解,我到底做错了什么?UpdatePerson已绑定(?)
这是教程repo:和博客文章
UpdatePerson已绑定(?)
不,它不是。这只是一个正常的功能,您可以导入
为了使其发挥redux
流程循环的作用,您需要dispatch
此功能
当您没有传递mapDispatchToProps
时,您将获得dispatch
功能作为连接组件的道具,因此要使用它,您必须按照以下方式执行:
this.props.dispatch(updatePerson())
如果您决定将mapDispatchToProps
传递给connect
,则您将不会收到dispatch
作为道具,但您可以使用它包装您的操作:
const mapDispatchToProps = dispatch => {
return {
updatePerson: () => {
dispatch(updatePerson())
}
}
}
或者您可以只传递一个对象:
const mapDispatchToProps = {
updatePerson,
deletePerson
}
另一种方法是使用bindActionCreators
(就像你在文章中提到的那样)
使用此方法,您可以使用以下代码行分派操作:
function mapDispatchToProps(dispatch) {
return bindActionCreators({
updatePerson: updatePerson,
deletePerson: deletePerson
}, dispatch);
}
这样称呼它:
this.props.updatePerson()
请注意,如果键与变量匹配,则可以使用
function mapDispatchToProps(dispatch) {
return bindActionCreators({
updatePerson,
deletePerson
}, dispatch);
}
bindActionCreators
的另一个好方法是将所有动作作为别名导入(甚至是来自不同文件的不同动作):
然后将它们全部堆叠在一个对象中(如果需要,也可以将它们分开):
现在,您可以通过操作
对象引用任何操作:
this.props.actions.myAction();
this.props.actions.myOtherAction();
您可以阅读我在中的各种选项,但您应该能够使用该代码分派操作,而不需要actionCreator本身中的分派调用(因为bindActionCreators正在向它们“添加”分派)(?)操作创建者只是一个返回操作的普通函数(对象
)。如果不发送它,您只需返回它返回的对象。当使用dispatch
时,您可以让它在redux
流中“播放”,因此还原程序
或中间件
可以在调用时捕获它们。
function mapDispatchToProps(dispatch) {
return bindActionCreators({
updatePerson,
deletePerson
}, dispatch);
}
import * as userActions from '../url';
import * as otherActions from '../otherUrl';
function mapDispatchToProps(dispatch) {
const combinedActions = { ...userActions, ...otherActions };
return {
actions: bindActionCreators(combinedActions, dispatch)
};
}
this.props.actions.myAction();
this.props.actions.myOtherAction();