【问题标题】:Why ES6 Imported Object's Child Return Undefined?为什么 ES6 导入对象的子对象返回未定义?
【发布时间】:2020-04-23 09:13:46
【问题描述】:

这是我的代码:

import * as _routes from '../../routes'
console.log('parent:', _routes)
console.log('child:', _routes.breadcrumb)

结果如下:

如果_routes 返回一个以breadcrumb 作为子对象之一的对象, 为什么_routes.breadcrumb返回undefined

【问题讨论】:

  • 很可能,breakcrumb 在您登录时是 undefined,稍后会设置。我猜你的模块图中有一个依赖循环。
  • 您需要解决依赖循环。导入一次运行一个,因此您可能会看到这一点,因为任何文件调用 import * as _routes from '../../routes';routes 导入或其他导入,所以 breadcrumb 没有时间运行,因为我们仍在运行该文件的导入。

标签: javascript ecmascript-6 import module


【解决方案1】:

没关系。

根据@loganfsmyth 的评论,breadcrumbconsole.log 被触发时很可能是undefined,并在稍后设置。延迟之类的。所以我只使用setTimeout classic hack。

import * as _routes from '../../routes'
console.log('parent:', _routes)

setTimeout(function(){
  console.log('child:', _routes.breadcrumb)
}, 100)

这是临时解决方案,但总比没有好。 仍然不知道具体是什么问题,所以如果有人有解释,请分享。谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2019-01-21
    • 1970-01-01
    • 2020-07-24
    • 2012-01-05
    • 2019-11-30
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多