dispatch和bindActionCreators之间有什么区别?

Gor*_*ath 20 reactjs react-redux

如果我们通过使用调度连接到操作,有两种方式: -

1. this.props.dispatch(requestEmployees());

2. const mapDispatchToProps = (dispatch) => ({
      requestEmployees: () => dispatch(requestEmployees())

    });
Run Code Online (Sandbox Code Playgroud)

如果我们在bindActionCreators的帮助下做同样的事情,那么我们的代码将是: -

function matchDispatchToProps(dispatch) {
        return bindActionCreators({ editLabResult: requestEmployees}, dispatch);
    }
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,我应该使用dispatch还是 bindActionCreators?他们之间有什么区别?

Ori*_*ori 33

这实际上是一回事.的结果

bindActionCreators({ editLabResult: requestEmployees}, dispatch);
Run Code Online (Sandbox Code Playgroud)

是你手动创建的:

requestEmployees: () => dispatch(requestEmployees())
Run Code Online (Sandbox Code Playgroud)

根据redux bindActionCreators文档:

将值为动作创建者的对象转换为具有相同键的对象,但将每个动作创建者包装到分派 调用中,以便可以直接调用它们.

bindActionCreators({ editLabResult: requestEmployees, anotherAction, etc... }, dispatch);
Run Code Online (Sandbox Code Playgroud)

而不是使用的bindActionCreators,您可以将对象传递给connect方法,它会做包装为您提供:

connect(mapStateToProps, { editLabResult: requestEmployees, anotherAction, etc... })
Run Code Online (Sandbox Code Playgroud)