【问题标题】:ES6 modules - imported constants undefined if not in React componentES6 模块 - 如果不在 React 组件中,导入的常量未定义
【发布时间】:2020-09-30 06:34:26
【问题描述】:

我发现的唯一类似问题是this one,但我看不出在这种情况下我会如何导致循环依赖:

我有一个像这样导出常量的文件:

(选择数组版本用于选​​择输入,另一个用于防止在条件检查中输入错误)

payments.constants.js

export const paymentMethodChoices = [
    { id: "Cash", name: "Cash" },
    { id: "BankTransfer", name: "BankTransfer" },
];

export const paymentMethods = {
    Cash: paymentMethodChoices[0],
    BankTransfer: paymentMethodChoices[1],
}

当它们被导入到我的任何 react 组件中时,一切都按预期工作。

MyReactComponent.js

import React from 'react';
import { paymentMethods } from '../../../constants';

const defaultValues = () => {    
    console.log("const object is available", paymentMethods)
    
    return {
        paymentMethod: paymentMethods.Cash.id,
        /* ... other scalar values*/
    }
};

const MyReactComponent = (props) => { ... }

但是当我尝试在另一个 js 文件中导入常量并将它们合并到另一个常量中时,我收到一个错误,说它们是 undefined:

defaultValues.js

import { paymentMethods } from '../../../../constants';

export const dailyCostCalendarDefaultValues = {    
    paymentMethod: paymentMethods.Cash.id,
    vatReturn: true,
};

错误消息:TypeError: Cannot read property 'Cash' of undefined

【问题讨论】:

  • 假设常量路径正确并且是相同的常量文件,我在您提供的代码中没有看到任何错误。可能需要更多上下文
  • 谢谢 - 也许我应该首先创建一个沙箱,我确信我一定遗漏了一些明显的东西。很快就会用沙盒更新问题。

标签: javascript reactjs ecmascript-6 undefined es6-modules


【解决方案1】:

好的,最后它确实是一个循环依赖,但由于文件导入链很长,所以它非常复杂。比如:

- external.js - file where the parent.js is imported    
|
 ... - parent.js - deeply nested parent file importing fileWithProblem.js
    |
     -- fileWithProblem.js - importing external.js

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 2020-08-24
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多