简体   繁体   English

在 NextJS 中使用带有动态组件的 switch 语句

[英]Using switch statement with dynamic components in NextJS

I am trying to use dynamic import in NextJS and I do not understand why it works only while storing imported component in a variable.我正在尝试在 NextJS 中使用动态导入,但我不明白为什么它仅在将导入的组件存储在变量中时才起作用。 It breaks when I try to return it from other function.当我尝试从其他函数返回它时它会中断。

It works this way:它是这样工作的:

import dynamic from "next/dynamic";


const Article = dynamic(() => import("tutorial/ru/welcome.mdx"));

but like this, well, it breaks:但像这样,好吧,它打破了:

import dynamic from "next/dynamic";

export default ({ route }) => {
  switch (route) {
    case "ru":
    default:
      return dynamic(() => import("tutorial/ru/welcome.mdx"));
  }
};

I get the Invalid hook call.我收到了Invalid hook 调用。 Hooks can only be called inside of the body of a function component message.钩子只能在函数组件消息的主体内部调用

I think you need to export it , then try to use it like so :我认为您需要导出它,然后尝试像这样使用它:

import dynamic from "next/dynamic";


const Article = dynamic(() => import("tutorial/ru/welcome.mdx"));

export default Article;

then try to use it in switch statement :然后尝试在 switch 语句中使用它:

import Article from './Article';
export default ({ route }) => {
  switch (route) {
    case "ru":
     return (<></>)
    default:
      return <Article />;
  }
};

I found a solution to get over this issue!我找到了解决这个问题的方法!

import dynamic from "next/dynamic";

import Loader from "components/Loader/Loader";
import Error from "pages/_error";

export default ({ route }) => {
  const Article =  dynamic(
    () => import(`tutorial/${route}.mdx`).catch(err => {
      return () => <Error />
    }),
    { loading: () => <Loader /> }
  );
  return <Article />
};

I should store the component in the variable after all, but I get the component itself dynamically using literal strings, and after that I return the component as tag ().毕竟我应该将组件存储在变量中,但是我使用文字字符串动态获取组件本身,然后我将组件作为标签 () 返回。 Works fine now!现在工作正常!

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

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