【发布时间】: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])
为什么第一个可以工作,但第二个有找不到模块错误,这两行代码之间有什么区别,任何人都可以帮忙吗?
【问题讨论】:
-
见How do I dynamically import images in React?。你也可以写
const Lzy = React.lazy(() => import(currentConfig.componentPath + ''));这会起作用。