可以在所有容器组件中导入所有操作创建器

It's ok to import all action creators in all container components?

本文关键字:创建 导入 操作 组件      更新时间:2023-09-26

我有一个索引文件,我用不同的操作创建器为不同的视图导入不同的文件:

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

然后我每次导入actions索引包含所有的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)

如果我在不同的导出中分开,只导入我的容器需要的动作创建者,这是可以的吗?

同样,当我有很多动作创建者时,很可能很难找到没有被占用的名称。

你认为这是最好的方法吗?

我认为更好的解决方案是分别导出每个动作模块。我在我的项目中使用next架构:

所有动作的索引文件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 }

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

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

使用这种方法,您可以完全控制容器需要的操作。

只导入您需要的操作是一种常见的方法。我不明白你为什么要把所有的动作都捆绑在一个对象里。

您还可以像这样使用命名空间导入:

import * as generalActions from './generalActions'

在这种情况下,你不需要export default行动对象包含所有generalActions,你可以只export每个行动。

一般来说,最好只导入实际使用的内容。