Nextjs中基于getServerSideProps的动态导入

时间:2020-05-27 02:59:36

标签: reactjs next.js

我非常感谢您提供解决此问题的指导。在Next js中,我想基于从getServerSideProps获得的props.page.type导入动态组件。我的代码如下:

import { getPageBySlug } from '../../utils/pagesApiHelper'
import dynamic from 'next/dynamic'

// this is what I need to be dynamic and the way it is written below doesn't work:
const Content = dynamic(() => import(`../../components/${props.page.type}`))

const Page = ({ page }) => {
    return (
        <div>
            <h1>Some Title</h1>
            <Content />
        </div>
    )
}

export const getServerSideProps = async ({ params: { slug } }) => {
    const page = await getPageBySlug(slug)

    return {
        props: {
            page: page
        }
    }
}

export default Page

下面的代码有效,但是它不是服务器端呈现的,这是我需要的:

const Page = ({ page }) => {
    const Content = dynamic(() => import(`../../components/${page.type}`))
    return (
        <div>
            <h1>Some Title</h1>
            <Content />
        </div>
    )
}
Any ideas are greatly appreciated. Thanks in advance!

0 个答案:

没有答案