简体   繁体   English

我可以在 next.js 中使用带有 for 循环的动态导入吗?

[英]can i use dynamic import with for loop in next.js?

I'm going to use dynamic import when I need to bring in a lot of components.当我需要引入很多组件时,我将使用动态导入。 In this situation, is it possible to use 'for' loop?在这种情况下,是否可以使用“for”循环?

 import dynamic from "next/dynamic"; let Dynamic = []; for (let i = 1; i < 80; i++) { const DynamicComponent = dynamic(() => import(`../src/Templates/BlendyTemplate${i}`) ); Dynamic.push(DynamicComponent); } //this is just example.. const Home = () =>{ const [state,setState] = useState(0); let DynamicComponents = Dynamic[state] return <div> <button onClick={()=>{setState(state+1)}} <DynamicComponents/></div> } export default Home;

No you cannot generate the path dynamically:不,您不能动态生成路径:

Note: In import('path/to/component'), the path must be explicitly written.注意:在import('path/to/component')中,必须显式写入路径。 It can't be a template string nor a variable.它不能是模板字符串或变量。 Furthermore the import() has to be inside the dynamic() call for Next.js to be able to match webpack bundles / module ids to the specific dynamic() call and preload them before rendering.此外,import() 必须位于 Next.js 的 dynamic() 调用中,以便能够将 webpack 包/模块 ID 匹配到特定的 dynamic() 调用并在渲染之前预加载它们。 dynamic() can't be used inside of React rendering as it needs to be marked in the top level of the module for preloading to work, similar to React.lazy. dynamic() 不能在 React 渲染内部使用,因为它需要在模块的顶层标记才能预加载工作,类似于 React.lazy。

source来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM