NextJS - ReactDOMServer目前不支持Suspense。

9

我目前正在尝试将加载组件纳入使用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>
   </>
   )
}

我的问题是我遇到了一个错误,显示ReactDOMServer目前不支持Suspense,但我希望使用Suspense来在我的页面上启用加载屏幕。就像这个网站一样。

你正在使用哪个版本的 Next 和 React? - GeorgeButter
2个回答

8
你可以在Next.js中使用React 18的功能,如suspense 高级特性。显然,这仍处于试验阶段,并可能导致应用程序出现问题。
npm install next@latest react@rc react-dom@rc

要启用,使用实验标志concurrentFeatures: true
// next.config.js
module.exports = {
  experimental: {
    concurrentFeatures: true,
  },
}

一旦启用,您可以在所有页面中使用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>
  )
}

0
我曾遇到过类似问题。最终,我使用了 setStatecomponentDidMount 的组合来模拟 Suspense
render(){
    return this.state.browser ? <Component/> : <Placeholder/>
}

componentDidMount(){
    this.setState({browser: true})
}

希望它有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接