usePreventScroll在Nextjs中导致useLayoutEffect警告

时间:2020-10-31 13:59:22

标签: javascript reactjs next.js react-aria

我正在学习Next.js,并且正在尝试将class CommandHandler { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { /* method code goes here */ } } 软件包集成到我的项目中。我有一个布局组件,在这里我只是像这样调用@react-aria/overlays方法:

usePreventScroll

此布局组件用于我的 usePreventScroll({ isDisabled: true });

_app.js

导出默认应用;

进入浏览器并加载页面时,出现以下错误:

import { useEffect } from 'react'
import { useRouter } from 'next/router'
import * as gtag from '../lib/gtag'

import 'styles/vendor.scss';
import 'styles/globals.scss';

import Layout from 'components/layout';

import { SSRProvider } from '@react-aria/ssr';

const App = ({ Component, pageProps }) => {
  return (
      <SSRProvider>
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </SSRProvider>
  )
}

这是什么问题,我将如何解决?

我尝试将Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://reactjs.org/link/uselayouteffect-ssr for common fixes. at Layout (/home/bas/projects/test-website/build/server/pages/_app.js:718:3) at div at $c5f9596976ab8bd94c5879001549a3e$var$OverlayContainerDOM (/home/bas/projects/test-website/node_modules/@react-aria/overlays/dist/main.js:864:7) at ModalProvider (/home/bas/projects/test-website/node_modules/@react-aria/overlays/dist/main.js:810:5) at OverlayProvider at SSRProvider (/home/bas/projects/test-website/node_modules/@react-aria/ssr/dist/main.js:33:13) at UIContextProvider (/home/bas/projects/test-website/build/server/pages/_app.js:1144:74) at ManagedUIContext (/home/bas/projects/test-website/build/server/pages/_app.js:1105:3) at App (/home/bas/projects/test-website/build/server/pages/_app.js:5171:3) at AppContainer (/home/bas/projects/test-website/node_modules/next/dist/next-server/server/render.js:23:748) 组件包装在软件包Layout中。

2 个答案:

答案 0 :(得分:1)

下一个js将计算服务器上的第一页。因此它不了解浏览器滚动或本地存储或其他浏览器api。 您可以在代码块中添加检查,如果存在窗口对象或服务器中正在执行执行,然后执行usePreventDefault

    import {useIsSSR} from '@react-aria/ssr';

    function Layout() {
       let isSSR = useIsSSR();
 
       useEffect(() => {
         !isSSR && usePreventScroll({ ... }) 
       }, [isSSR])
    }

答案 1 :(得分:1)

您可以动态加载组件并禁用SSR:

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

该代码示例摘自NextJS docs。如果那不是您的事,只要processs.browser为true,就可以调用该钩子或渲染该组件。