如何组织 Redux Action-Creators 以在 Redux-React 中使用

How to organize Redux Action-Creators for use in Redux-React

我正在为我的项目使用 react-redux & redux-thunk

我必须使用 connect 将我的 actions 注入组件。

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

我的任务更上一层楼。我不想只以这种形式注入多个动作:

{
  doThis(),
  doThat()
}

但在这种形式中:

{
  this: {
    doThis1(),
    doThis2()
  }
  that: {
    doThat()
  }
}

所以基本上我的问题是我想分发多个动作创建者文件因为我希望它们这样组织。

我试过这个版本,但显然不起作用,因为调度没有注入每个 Thunk Action Creator:

import * as actions from './actions'

const mapDispatchToProps = (dispatch) => {
  return {
    dataActions: {
      ...actions.dataActions
    }
  };
}

export default connect(null, mapDispatchToProps)(Component);

所以我的最后一个问题是:

我什至应该这样使用 Redux 吗?我可以这样组织我的文件吗?

如果您不希望每个动作创建者有一个 属性,而是希望在几个属性中构造您的绑定动作创建者,每个属性都包含一组动作创建者,您可以这样做:

import { bindActionCreators, .. } from 'redux';
..
const mapDispatchToProps = (dispatch) => {
  return {
    dataActions: bindActionCreators(actions.dataActions, dispatch),
    otherActions: bindActionCreators(actions.otherActions, dispatch),
    ..        
  };
};

bindActionCreators 的第一个参数是包含动作创建器函数的对象(例如,仅导出动作创建器的导入模块)。在您的实际组件中,您应该能够使用 this.props.dataActions.someDataAction(..).

如果问题只是关于您是否可以将不同的动作创建者保存在不同的文件中,您可能甚至不想将动作创建者分组,而只是这样做:

return {
  ...bindActionCreators(actionCreatorsFromOneModule, dispatch),
  ...bindActionCreators(actionCreatorsFromAnotherModule, dispatch),
  ..        
};