React Apollo 错误:不变违规:在上下文中找不到“客户端”或作为选项传入

新手上路,请多包涵

我正在使用 React、Apollo 和 Next.js 构建一个项目。我正在尝试将 react-apollo 更新到 3.1.3,现在查看站点时出现以下错误。

不变违规:在上下文中找不到“客户端”或作为选项传入。将根组件包装在 中,或通过选项传入 ApolloClient 实例。

如果我将 react-apollo 包降级到 2.5.8,它可以正常工作,所以我认为 2.5 和 3.x 之间发生了一些变化,但在 react-apollo 或 next-with-apollo 文档中找不到任何内容来表明那可能是什么。任何帮助将不胜感激。

withData.js

 import withApollo from 'next-with-apollo';
import ApolloClient from 'apollo-boost';
import { endpoint } from '../config';

function createClient({ headers }) {
    return new ApolloClient({
        uri: endpoint,
        request: operation => {
            operation.setContext({
                fetchOptions: {
                    credentials: 'include'
                },
                headers
            });
        },
        // local data
        clientState: {
            resolvers: {
                Mutation: {}
            },
            defaults: {}
        }
    });
}

export default withApollo(createClient);

_app.js

 import App from 'next/app';
import { ApolloProvider } from 'react-apollo';
import Page from '../components/Page';
import { Overlay } from '../components/styles/Overlay';
import withData from '../lib/withData';

class MyApp extends App {
    static async getInitialProps({ Component, ctx }) {
        let pageProps = {};
        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(ctx);
        }

        // this exposes the query to the user
        pageProps.query = ctx.query;
        return { pageProps };
    }

    render() {
        const { Component, apollo, pageProps } = this.props;

        return (
            <ApolloProvider client={apollo}>
                <Overlay id="page-overlay" />
                <Page>
                    <Component {...pageProps} />
                </Page>
            </ApolloProvider>
        );
    }
}

export default withData(MyApp);

原文由 Keith 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 812
2 个回答

就我而言,我发现我安装了 react-apollo@3.0.1 以及 @apollo/react-hooks@3.0.0 。删除 @apollo/react-hooks 并仅依靠 react-apollo 为我解决了不变的问题。确保您没有在锁定文件中使用任何不匹配的版本或 package.json

这是有人在 GitHub 问题线程中所说的,对我来说也是如此。一定要试试!

原文由 Duma Cristian 发布,翻译遵循 CC BY-SA 4.0 许可协议

我有多种解决方案,我认为这确实归结为您最初如何设置所有相关包。

“在将客户端连接到 Reacts 时,有些包与其他包不能很好地配合使用 Context.Provider

我有两个似乎运行良好的两个修复程序(对于新项目和更新旧项目):

1:卸载 @apollo/react-hooks

然后:

 import { ApolloProvider } from "@apollo/client";

代替:

 import { ApolloProvider } from "react-apollo";

(这让我可以保持“@apollo/react-hooks”包没有冲突)

3:仔细检查正在服务的服务器 HttpLink 客户端 URI 是否已启动并正在运行以供客户端连接(这给出了一个不同的错误,然后那个正在谈论但仍然是在这种情况下很高兴知道)

结论: 可能会有点试错,但请尝试使用匹配/配对包

原文由 Willie Doc Wright 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题