【问题标题】:Exporting function in ES6 / reactES6/react 中的导出函数
【发布时间】:2017-12-29 11:47:26
【问题描述】:

在服务器端(nodejs/express),我在导出和引用这个文件时没有问题(使用 Attempt1)。

// collectionFile.js
function collection() {
    let data = {};
    function getData(key) {
        return data[key];
    }
    function setData(key, value) {
        data[key] = value;
    }
    return {
        getData: getData,
        setData: setData
    };
}

const instanceOfCollection = collection();

在客户端 (React) 上,我无法引用和访问 getData 函数。以下是我尝试过的一些组合。它们都不起作用。我怎样才能让它工作?

// Attempt1: export
// module.exports.getter = instanceOfCollection.getData;

// Attempt1: import
// const getter = require('./collectionFile').getter;
// Uncaught TypeError: getter is not a function

// Attempt2: export
// export default { instanceOfCollection };

// Attempt2: import
// import instanceOfCollection from './collectionFile';
// const instance = instanceOfCollection.getData;
// Uncaught TypeError: Cannot read property 'getData' of undefined

// Attempt3: export
// export const instanceOfCollection = collection();

// Attempt3: import
// import { instanceOfCollection } from './collectionFile';
// const instance = instanceOfCollection.getData;
// Uncaught TypeError: Cannot read property 'getData' of undefined

编辑:原来我是从文件 B 中引用文件 A 以及之前从文件 A 中引用文件 B

【问题讨论】:

  • 能否包含您的文件结构?
  • 您是在使用模块捆绑器还是只是几个 javascript 文件?
  • 同一文件夹中只有 2 个文件。我正在从另一个文件中导入 collectionFile.js。请注意,我在导出常量时没有任何问题
  • 就几个js文件

标签: javascript reactjs ecmascript-6 es6-modules


【解决方案1】:

有很多方法可以做这样的事情:

  1. ES5 导出

    module.export = instanceOfCollection

    然后

    var getData = require('my_module').getData

  2. ES6 导出

    export default instanceOfCollection

    然后

    import { getData, setData } from 'my_module'

  3. ES6 命名导出

    export const setter = instanceOfCollection.setData export const getter = instanceOfCollection.getData

    然后

    import { setter, getter } from 'my_module'

    import * as myCollection from 'my_module' myCollection.getter() myCollection.setter()

  4. ES5 重命名

    module.export = { getter: instanceOfCollection.getData, setter: instanceOfCollection.setData, }

    然后

    const { setter, getter } = require('my_module')

    const getter = require('my_module').getter const setter = require('my_module').setter

希望其中一些对你有用。

【讨论】:

  • import { getData, setData } from 'my_module' 不起作用。我正在尝试其他的。
  • @KayaToast 你知道我是如何导出它的吗?没有大括号!
  • 是的,我对牙套很小心。我都试过了。它们都不起作用。感谢您的建议。
  • @KayaToast 我不确定你在做什么,但我现在正在我的机器上测试它,它运行良好。
  • 当我尝试从其他文件引用时,您的最后一种方法有效。原来我是从文件 B 中引用文件 A 以及从文件 A 中引用文件 B。
猜你喜欢
  • 2017-02-23
  • 1970-01-01
  • 2016-06-03
  • 2018-08-16
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 2019-08-07
相关资源
最近更新 更多