【问题标题】:How do you organise actions in Redux?你如何在 Redux 中组织动作?
【发布时间】:2017-10-28 06:12:34
【问题描述】:

我有一个名为 actions 的文件夹,其中包含一个名为 index.js 的文件,到目前为止,我已将所有操作都放入其中。现在变得很混乱,我想知道如何最好地分割东西。有什么好的策略吗?您是否将它们保存在不同的文件中?按...分组?还是您只是将它们作为部分保存在不同的文件中,然后将它们包含在索引文件中,然后始终只导入索引文件?

【问题讨论】:

    标签: reactjs architecture redux flux


    【解决方案1】:

    将所有内容放在一个 action.js 中会很快失控,reducers 也是如此。

    这确实归结为个人喜好,但我看到的趋势似乎是将应用程序分成功能,其中每个功能都通过自己的操作隔离,并且每个功能也有一个 reducer。

    应用程序树的每一层都将组合减速器,您的商店最终将看起来像文件夹结构,从而更容易找到东西。一个特性通常包含actions.js、reducer、js、index.jsx,也可能包含该特性的style.scss/css。这样做的好处是,在某些时候删除该功能非常容易,而不必到处寻找死代码。

    您没有提及如何捆绑代码。使用前 Webpack 构建时,这种方法很好。

    【讨论】:

      【解决方案2】:

      您可以使用bindActionCreators (http://redux.js.org/docs/api/bindActionCreators.html)。

      小例子:

      import React, { Component } from 'react'; 
      import { connect } from 'react-redux'; 
      import { bindActionCreators } from 'redux';
      import * as filterActions from '../actions/filterActions';
      import * as writeActions from '../actions/writeActions';
      
      class TestComponent extends Component {
        render(){
          return <div>Test</div>;
        }
      }
      
      
      function mapDispatchToProps(dispatch){
        return {
          filterActions: bindActionCreators(filterActions, dispatch),
          writeActions: bindActionCreators(writeActions, dispatch)
        };
      }
      
      export default connect(null, mapDispatchToProps)(TestComponent);
      

      这会将动作添加到组件的 props 中(在 mapDispatchToProps 的返回对象中使用的键处)。因此,如果您想使用 filterActions 中的操作,可以使用this.props.filterActions.actionName()

      【讨论】:

        猜你喜欢
        • 2011-05-13
        • 2011-08-21
        • 2018-03-05
        • 1970-01-01
        • 2010-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-12
        相关资源
        最近更新 更多