【问题标题】:Is there a way to require in multiple modules into a file, which is then exported again as a single module?有没有办法将多个模块要求放入一个文件中,然后将其作为单个模块再次导出?
【发布时间】:2018-10-14 01:00:57
【问题描述】:

目前正在使用 Redux,想知道是否有办法将多个模块中的 require 放入一个文件中,然后再次导出为单个模块?

例如,在我的actions/bookmark.js 中,我对所有与书签相关的操作进行了相应的分组:

module.exports = {
  fetchBookmarkList: () => {
    return {
      type: 'FETCH_LIST'
    }
  },
  fetchBookmark: () => {
    return {
      type: 'FETCH_BOOKMARK'
    }
  }
}

然后在我的actions/index.js 文件中,我需要所有操作组(包括书签操作以及其他操作)。然后我想将整个文件导出为单个模块。

大致上我想到了这样的事情(显然这段代码不起作用):

actions/index.js:

module.exports = {
  require('./bookmark');
  require('./tags');
}

我想这样做的原因是我只需要导入一个包含我所有操作的操作文件(即actions/index.js 文件):

示例组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';

class BookmarkList extends Component {
  constructor(props) {
    super(props);
    this.props.fetchBookmarkList();
  }

  render() {
    return (
      <div></div>
    );
  }
}

export default connect(null, actions)(BookmarkList);

【问题讨论】:

    标签: reactjs module redux export require


    【解决方案1】:

    建议您将所有操作传递给 mapDispatchToProps,只传递您的组件所需的操作

    但是你可以在actions/index.js中使用:

    使用扩展运算符:

    module.exports = {
      ...require('./bookmark');
      ...require('./tags');
    } 
    

    在 ES6 语法中:

    actions/index.js:

    export * from './bookmark'
    export * from './tags'
    

    【讨论】:

    • spread operator 版本似乎不起作用,但 ES6 版本可以。谢谢!
    【解决方案2】:

    我在组件中看到你的 es6 模块语法,为什么不在你的 redux 文件中?

    export const fetchBookmarkList = () => {
      return {
        type: 'FETCH_LIST'
      }
    };
    
    export const fetchBookmark = () => {
      return {
        type: 'FETCH_BOOKMARK'
      }
    }
    

    基于this reference,我认为可以像这样重新导出所有内容:

    export * from './bookmark'
    export * from './tags;
    

    但没试过,我可能错了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2017-06-12
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多