【问题标题】:React lazy import can't import the component if use string varibaleReact惰性导入无法导入使用字符串变量的组件
【发布时间】:2022-01-23 13:43:57
【问题描述】:

在我的项目中,我有一个组件根据当前 URL 渲染子节点,它使用 React.lazy 导入子组件。我按照这个post answer's 代码示例实现它。

我在实现的时候注意到一个奇怪的事情,如果我像下面的代码所示使用模板字符串导入组件,它工作正常。

const Lzy = React.lazy(() => import(`${currentConfig.componentPath}`));

但是当我直接使用变量导入组件时,它总是在网页上显示错误消息。

const Lzy = React.lazy(() => import(currentConfig.componentPath));


错误信息:

Error: Cannot find module './home/order/OrderForm'
(anonymous function)
src/features lazy groupOptions: {} namespace object:5

currentConfig 对象的数组

const pathConfig = [{path: "/dashboard/order/new", componentPath: './home/order/OrderForm'}]

代码sn-p

    const [CurrentChild, setCurrentChild] = useState(() => () => <div>loading...</div>)
useEffect(() => {
    let currentConfig = pathConfig.find(item => item.path === currentPath)
    if (!!currentConfig) {
        const Lzy = React.lazy(() => import(currentConfig.componentPath));
        //const Lzy = React.lazy(() => import(`${currentConfig.componentPath}`));
        setCurrentChild(Lzy)
    }
}, [currentPath])

为什么第一个可以工作,但第二个有找不到模块错误,这两行代码之间有什么区别,任何人都可以帮忙吗?

【问题讨论】:

标签: reactjs template-literals


【解决方案1】:

不能这样使用,可以参考ECMA Dochttps://262.ecma-international.org/6.0/#sec-imports

进口声明:

  • 导入 ImportClause FromClause ;
  • 导入 ModuleSpecifier ;

FromClause :

  • 来自模块说明符

模块说明符:

  • 来自 ModuleSpecifier

ModuleSpecifier 只能是 StringLiteral,不能是 AdditiveExpression 等任何其他类型的表达式。

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 2021-01-01
    • 2017-01-03
    • 1970-01-01
    • 2019-11-28
    相关资源
    最近更新 更多