NextJS - ReactDOMServer 尚不支持 Suspense

Nii*_*iic 9 next.js

我目前正在尝试将加载器组件合并到使用 NextJS 构建的网站中。我想使用 Suspense 显示加载屏幕,可能是在刷新页面或更改路线后。我的代码是这样的:

import Head from 'next/head'
import { Loader } from '../components/loader'
const { Suspense } = require('React')

function MyApp({ Component, pageProps }) {
   return (
   <>
     <Suspense fallback={<Loader />}>
        <Head>
         .... some codes such as meta tags, title tags ....
        </Head>
      <Component {...pageProps} />;
      </Suspense>
   </>
   )
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我收到一条错误,指出ReactDOMServer 尚不支持 Suspense。但我想使用 Suspense 在我的页面上启用加载屏幕。很像这个网站

Tom*_*cks 8

您可以使用 React 18 功能,例如suspenseNext.js高级功能。显然它仍处于实验阶段,可能会导致您的应用程序出现问题。

npm install next@latest react@rc react-dom@rc
Run Code Online (Sandbox Code Playgroud)

要启用,请使用实验标志concurrentFeatures: true

// next.config.js
module.exports = {
  experimental: {
    concurrentFeatures: true,
  },
}
Run Code Online (Sandbox Code Playgroud)

启用后,您可以对所有页面使用 Suspense 和 SSR 流。

import dynamic from 'next/dynamic'
import { lazy, Suspense } from 'react'

import Content from '../components/content'

// These two ways are identical:
const Profile = dynamic(() => import('./profile'), { suspense: true })
const Footer = lazy(() => import('./footer'))

export default function Home() {
  return (
    <div>
      <Suspense fallback={<Spinner />}>
        {/* A component that uses Suspense-based */}
        <Content />
      </Suspense>
      <Suspense fallback={<Spinner />}>
        <Profile />
      </Suspense>
      <Suspense fallback={<Spinner />}>
        <Footer />
      </Suspense>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)