如何修复此警告 "useLayoutEffect" 相关的警告?

How to fix this warning "useLayoutEffect" related warning?

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

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 fb.me/react-uselayouteffect-ssr for common fixes.

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

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

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' });

我在使用 jest、enzyme 和 Material UI 时遇到了同样的问题,但我没有使用 Apollo。如果您在使用 Material UI 时遇到此问题,一个简单的解决方法是将以下内容添加到您的测试配置文件 (src/setupTests.js) 中:

import React from 'react';

React.useLayoutEffect = React.useEffect;

来源:here and and here.

否则,如果您的堆栈包括 Apollo,您可以