dispatch 和 bindActionCreators 有什么区别? [英] What is difference between dispatch and bindActionCreators?
问题描述
如果我们使用 dispatch 连接到 action,有两种方式:-
<代码>1.this.props.dispatch(requestEmployees());2. const mapDispatchToProps = (dispatch) =>({requestEmployees: () =>调度(请求员工())});
<块引用>
如果我们在 bindActionCreators 的帮助下做同样的事情,那么我们的我们将成为的代码:-
function matchDispatchToProps(dispatch) {return bindActionCreators({ editLabResult: requestEmployees}, dispatch);}
<块引用>
现在我的问题是,我应该使用dispatch 还是bindActionCreators?它们之间有什么区别?
实际上是一回事.
的结果bindActionCreators({ editLabResult: requestEmployees}, dispatch);
是您手动创建的:
requestEmployees: () =>调度(请求员工())
<小时>
根据 redux bindActionCreators
文档:
将一个值为 action creators 的对象变成一个对象相同的键,但每个动作创建者都包含在调度中调用以便可以直接调用它们.
bindActionCreators({ editLabResult: requestEmployees, anotherAction, etc... }, dispatch);
您可以将对象传递给 connect
方法,它会为你做包装:
connect(mapStateToProps, { editLabResult: requestEmployees, anotherAction, etc... })
If we are connecting to the action by using the dispatch there are two way:-
1. this.props.dispatch(requestEmployees());
2. const mapDispatchToProps = (dispatch) => ({
requestEmployees: () => dispatch(requestEmployees())
});
If we are doing the same with the help of bindActionCreators then our code we will be:-
function matchDispatchToProps(dispatch) {
return bindActionCreators({ editLabResult: requestEmployees}, dispatch);
}
Now my question is, which one I should use dispatch or bindActionCreators? What is the difference between them?
It's actually the same thing. The result of
bindActionCreators({ editLabResult: requestEmployees}, dispatch);
Is what you've manually created:
requestEmployees: () => dispatch(requestEmployees())
According to the redux bindActionCreators
documentation:
Turns an object whose values are action creators, into an object with the same keys, but with every action creator wrapped into a dispatch call so they may be invoked directly.
bindActionCreators({ editLabResult: requestEmployees, anotherAction, etc... }, dispatch);
Instead of using bindActionCreators
, you can pass the object to the connect
method, and it will do the wrapping for you:
connect(mapStateToProps, { editLabResult: requestEmployees, anotherAction, etc... })
这篇关于dispatch 和 bindActionCreators 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!