1

Next.js 实现动态引入,实现对非 SSR 组件的支持

 2 years ago
source link: https://www.ixiqin.com/2022/05/08/next-js-to-realize-dynamic-introduction-implementation-of-ssr-components/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

CAPTCHA

Next.js 实现动态引入,实现对非 SSR 组件的支持

在使用 Next.js 进行开发的时候,会遇到某些组件是不提供 SSR 支持的(很正常,毕竟 SSR 是一个相对比较小众的应用场景。此外,某些组件会依赖浏览器环境的上下文),在这种情况下,我们需要一种方式来实现对非 SSR 组件的支持。

一般而言, 有两种方式,一种是使用 useEffects 来控制组件的载入,从而实现只在客户端层面加载组件,服务端渲染的时候就不再加载该组件。

另外一种方式是可以考虑借助于 Next.js 自带的 Dynamic Import 的特性,来完成组件的引入。

在使用层面比较简单,引入组件的方式从直接引入改为最外层套一层 dynamic 函数即可

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/hello3'),
  { ssr: false }
)

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  )
}

export default Home

这个问题的解决让我再次激起了对于 Next.js 的兴趣。过去因为不确定如何解决在浏览器和客户端环境下的问题,对于 Next.js 有些畏难;如今问题已解决,可以继续放心的使用 Next.js 了。

https://nextjs.org/docs/advanced-features/dynamic-import

本条目发布于2022年5月8日。属于Next.js分类,被贴了 next.js 标签。 ← 那些影响你前端开发体验的问题(1)

发表评论 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

评论 *

显示名称 *

电子邮箱地址 *

网站地址

在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。

如果有人回复我的评论,请通过电子邮件通知我。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK