可以导入所有容器组件中的所有动作创建者吗?

时间:2016-08-24 19:02:32

标签: javascript reactjs ecmascript-6 redux

知道我有一个索引文件,我用不同的视图导入不同的文件和动作创建者:

import generalActions from './generalActions'
import vftActions from './vftActions'
import shareActions from './shareActions'
import codeFormActions from './codeFormActions'
import signupActions from './signupActions'

const actions = {
    ...generalActions,
    ...vftActions,
    ...shareActions,
    ...codeFormActions,
    ...signupActions
}

export default actions

然后我每次都使用所有操作导入动作索引:

import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import actions from '../../redux/actions'

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actions, dispatch)
    }
}

export default connect(null, mapDispatchToProps)(ContainerComponent)

如果我在不同的导出中将其分开并仅导入我的容器需要的动作创建器,那么它可以吗?

同样有了这个,很可能当我有很多动作创作者时,很难找到没有采取的名字。

您认为它是最好的方法吗?

2 个答案:

答案 0 :(得分:10)

我认为更好的解决方案是单独导出每个操作模块。 我在我的项目中使用了下一个架构:

所有操作actions/index.js的索引文件:

// just import actions from other files (modules)
import * as notification from './notification'
import * as friend from './friend'
import * as profile from './profile'

// export all actions as modules
export { notification }
export { friend }
export { profile }

之后,在我的Container中,我只从actions/index.js导入我需要的内容:

import { notification,
         profile } from '../actions'

通过这种方法,您可以完全控制容器所需的操作。

答案 1 :(得分:2)

仅导入您需要的操作是执行此操作的常用方法。我不明白为什么你需要将所有动作捆绑在一个对象中。

你也可以像这样使用命名空间导入:

import * as generalActions from './generalActions'

在这种情况下,您不需要export default包含所有generalActions export的操作对象,您只需hard reload and empty cache每个操作。

通常,仅导入您实际使用的内容是一种很好的做法。