Dynamic Importing of an unknown component - NextJs

拥有回忆 提交于 2020-12-12 08:26:15

问题


I want to load a component dynamically based on the route. I'm trying to make a single page which can load any individual component for testing purposes.

However whenever I try to do import(path) it shows the loader but never actually loads. If I hard code the exact same string that path contains then it works fine. What gives? How can I get nextjs to actually dynamically import the dynamic import?

// pages/test/[...component].js

const Test = () => {
  const router = useRouter();
  const { component } = router.query;
  const path = `../../components/${component.join('/')}`;

  console.log(path === '../../components/common/CircularLoader'); // prints true

  // This fails to load, despite path being identical to hard coded import
  const DynamicComponent = dynamic(() => import(path), {
    ssr: false,
    loading: () => <p>Loading...</p>,
  });

  // This seems to work
  const DynamicExample = dynamic(() => import('../../components/Example'), {
    ssr: false,
    loading: () => <p>Loading...</p>,
  });

  return (
    <Fragment>
      <h1>Testing {path}</h1>
      <div id="dynamic-component">
        <DynamicComponent />      <!-- this always shows "Loading..." -->
        <DynamicExample /> <!-- this loads fine. -->
      </div>
    </Fragment>
  );
};

export default Test;

回答1:


I put dynamic outside of the component, and it work fine.

const getDynamicComponent = (c) => dynamic(() => import(`../components/${c}`), {
  ssr: false,
  loading: () => <p>Loading...</p>,
});

const Test = () => {
  const router = useRouter();
  const { component } = router.query;
  
  const DynamicComponent = getDynamicComponent(component);

  return <DynamicComponent />
}



回答2:


It happens because router.query is not ready and router.query.component is undefined at the very first render of dynamic page.

This would print false at first render and true at the following one.

 console.log(path === '../../components/common/CircularLoader');

You can wrap it with useEffect to make sure query is loaded.

const router = useRouter();

useEffect(() => {
  if (router.asPath !== router.route) {
    // router.query.component is defined
  }
}, [router])

SO: useRouter receive undefined on query in first render

Github Issue: Add a ready: boolean to Router returned by useRouter



来源:https://stackoverflow.com/questions/62942727/dynamic-importing-of-an-unknown-component-nextjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!