【问题标题】:NextJS dynamic routes with dynamic componentNextJS 动态路由与动态组件
【发布时间】:2022-06-12 21:39:20
【问题描述】:

我想创建 3 个动态页面,每个页面都有不同的渲染组件。

// components/AboutPage.js
export default function AboutPage({ template }){
  return <h1>{template}</h1>
}
// components/ContactPage.js
export default function ContactPage({ template }){
  return <h1>{template}</h1>
}
// components/BlogPage.js
export default function BlogPage({ template }){
  return <h1>{template}</h1>
}

还有路由文件。

// pages/[slug].js
import AboutPage from '../components/AboutPage'
import BlogPage from '../components/BlogPage'
import ContactPage from '../components/ContactPage'

export default function DynamicPage({ page }) {
  switch (page?.template) {
    case 'aboutPage':
      return <AboutPage {...page} />
    case 'blogPage':
      return <BlogPage {...page} />
    case 'contactPage':
      return <ContactPage {...page} />
    default:
      return null
  }
}

export const getStaticPaths = () => {
  const page = {
    template: 'aboutPage',
    slug: 'about'
  }
  return {
    props: {
      page
    }
  }
}

export const getStaticPaths = () => {
  const fetchedData = [
    {
      template: 'aboutPage',
      slug: 'about'
    },
    {
      template: 'contactPage',
      slug: 'contact'
    },
    {
      template: 'blogPage',
      slug: 'blog'
    }
  ]

  return {
    paths: fetchedData.map(({ slug }) => ({ params: {slug} })),
    fallback: 'blocking'
  }
}

我的网站是在构建时生成的,我担心的是最终的 JavaScript 包大小可能包括所有 3 个组件,即使页面是 AboutPage

我还没有看到任何相关的解决方案,NextJS 有 dynamic() 但不确定它是否对我的情况有帮助?或者我怎样才能使这项工作?

【问题讨论】:

标签: reactjs next.js


【解决方案1】:

您可以使用next/dynamic

添加:

const AboutPage = dynamic(
  () => import("../components/AboutPage"),
);

而不是

import AboutPage from '../components/AboutPage'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 2021-08-12
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2020-12-19
    相关资源
    最近更新 更多