如何修复此警告“useLayoutEffect”相关警告?

asi*_*aho 4 material-ui server-side-rendering react-apollo next.js react-hooks

我将 NextJS 与 Material UI 和 Apollo 结合使用。虽然一切正常,但警告没有消失。在我看来,很多 Material UI 组件都在使用useLayoutEffect,这是 React 发出的警告。错误如下。

警告:useLayoutEffect 在服务器上不执行任何操作,因为它的效果无法编码为服务器渲染器的输出格式。这将导致初始的、非水合的 UI 与预期的 UI 之间不匹配。为了避免这种情况,useLayoutEffect 应该只在专门在客户端渲染的组件中使用。请参阅 fb.me/react-uselayouteffect-ssr 了解常见修复。

asi*_*aho 5

问题已经解决了。我怀疑它发生在 Material UI 上,但它实际上发生在 Apollo 上。我将解决方案发布在这里,以便让其他人知道。

在 Apollo 配置文件中,我需要说明应用程序正在使用服务器端渲染。请检查下面的代码。如果您不使用 TypeScript,则只需删除类型即可。在最后一行{ getDataFromTree: 'ssr' }对象解决了这个问题。我希望它能帮助你。

import { InMemoryCache } from 'apollo-cache-inmemory';
import ApolloClient from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import withApollo from 'next-with-apollo';

type Props = {
  ctx?: {};
  headers?: {};
  initialState?: {};
};

const createClient = ({ ctx, headers, initialState }: Props) =>
  new ApolloClient({
    cache: new InMemoryCache().restore(initialState || {}),
    link: createHttpLink({ uri: process.env.API_ENDPOINT })
  });

export default withApollo(createClient, { getDataFromTree: 'ssr' });

Run Code Online (Sandbox Code Playgroud)