【问题标题】:How to organize Redux Action-Creators for use in Redux-React如何组织 Redux Action-Creators 以在 Redux-React 中使用
【发布时间】:2018-03-05 06:20:05
【问题描述】:

我正在为我的项目使用react-reduxredux-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 吗?我可以这样组织我的文件吗?如果可以,如何?

【问题讨论】:

    标签: redux react-redux redux-thunk


    【解决方案1】:

    如果您不想为每个动作创建者拥有一个属性,而是希望将绑定的动作创建者构造成几个属性,每个属性都包含一组动作创建者,您可以执行以下操作:

    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),
      ..        
    };
    

    【讨论】:

      猜你喜欢
      • 2016-03-12
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2016-03-09
      • 2016-01-17
      相关资源
      最近更新 更多