首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >您选择了“页面/_app`”中的“`getInitialProps`”而退出了自动静态优化吗?

您选择了“页面/_app`”中的“`getInitialProps`”而退出了自动静态优化吗?
EN

Stack Overflow用户
提问于 2022-10-19 08:34:50
回答 1查看 25关注 0票数 0

我正在构建下一个js应用程序。在我的项目中,我收到了警告。有人能帮我摆脱那种警告吗。请帮帮我。

你好,我正在使用这样的自定义应用-

代码语言:javascript
复制
import { ColorScheme, ColorSchemeProvider, Global, MantineProvider } from '@mantine/core'
import { getCookie, setCookie } from 'cookies-next'
import { GetServerSidePropsContext } from 'next'
import { ThemeProvider } from 'next-themes'
import { AppProps } from 'next/app'
import { useState } from 'react'

type Props = AppProps & { colorScheme: ColorScheme }

export default function App({ Component, pageProps, colorScheme: _colorScheme }: Props) {
  const [colorScheme, setColorScheme] = useState<ColorScheme>(_colorScheme)

  const toggleColorScheme = (value?: ColorScheme) => {
    const nextColorScheme = value || (colorScheme === 'dark' ? 'light' : 'dark')
    setColorScheme(nextColorScheme)
    setCookie('mantine-ui-colorScheme', nextColorScheme, { maxAge: 60 * 60 * 24 * 30 })
  }

  return (
    <>
      {/* need add next-themes failback */}
      <Global styles={() => ({
        ':root': { background: '#fff', color: '#000' },
        '[data-theme="dark"]': { background: '#1A1B1E', color: '#C1C2C5' }
      })} />
      {/* next-themes theme provider */}
      <ThemeProvider enableSystem={false}>
        {/* mantine color scheme provider */}
        <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme}>
          <MantineProvider theme={{ colorScheme }} withGlobalStyles withNormalizeCSS>
            <Component {...pageProps} />
          </MantineProvider>
        </ColorSchemeProvider>
      </ThemeProvider>
    </>
  )
}
App.getInitialProps = ({ ctx }: { ctx: GetServerSidePropsContext }) => ({
  colorScheme: getCookie('mantine-ui-colorScheme', ctx) || 'light',
})

在那之后,当我构建我的项目时,我会收到这样的警告-

代码语言:javascript
复制
Warning: You have opted-out of Automatic Static Optimization due to `getInitialProps` in `pages/_app`. This does not opt-out pages with `getStaticProps`

如何消除这个警告?

EN

回答 1

Stack Overflow用户

发布于 2022-10-19 09:42:48

带有getInitialProps的页面按需运行。如果发生这种情况,next.js将无法执行Automatic Static Optimization。当Next.js检测到页面是静态的(可以预先录制)时,就会使用麻生太郎,这意味着它没有阻塞数据需求。此确定是由于页面中没有getServerSidePropsgetInitialProps

这就是为什么推荐getStaticProps而不是getInitialProps

不幸的是,getStaticProps在pages/_app上不可用。因此,我们可以在所有页面上添加getStaticProps。否则我们就得继续警告。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74122252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档