从组件访问 this.props.dispatch 和其他动作创建者

Access this.props.dispatch and other action creators from component

我想同时使用 this.props.dispatch 和我自己定义的动作创建器来从我的 React 视图组件中调度动作。

但是,如果我将 mapDispatchToProps 传递给 connect(),我将无法访问 this.props.dispatch。所以,这是我想出的解决方法:

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        updateRackGroup,
        cloneRackGroup,
        onSelectRack,
        onCloneRack,
        valRackChange,
        valRackAdd,
        onRackAction,
        valRackUpdate,
        dispatch
    }, dispatch);
}

function mapStateToProps({
    tempRackStates,
    rackGrpsAdded,
    invalidFields
}) {
    return {
        tempRackStates,
        rackGrpsAdded,
        invalidFields
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(RackgroupGenerator);

我不满意,因为 "it wraps dispatch within dispatch"。

那么在这种情况下是否有一种优雅的方式来访问原始调度方法?

您不需要通过 dispatchbindActionCreators。只需将其合并到绑定的动作创建者

function mapDispatchToProps(dispatch) {
    const actionCreators = bindActionCreators({
        actionCreator1,
        actionCreator2,
    }, dispatch);
    return { ...actionCreators, dispatch };
}

// or without the additional assignment
return {
    dispatch,
    ...bindActionCreators({ actionCreator1, actionCreator2 }, dispatch)
};

顺便说一句,我没有对它进行肯定的测试,但我也认为你不应该 "wrap dispatch with dispatch" 因为我相信它会导致奇怪的行为,例如多次不情愿地调度操作。