【问题标题】:next.js + GraphQL: "Invariant Violation: Could not find "client" in the context or passed in as an option...."next.js + GraphQL:“不变违规:在上下文中找不到“客户端”或作为选项传入......”
【发布时间】:2021-06-25 15:51:46
【问题描述】:

网上到处都有很多关于这个问题的帖子,但没有适合我的解决方案。

我收到错误:

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

这是我的代码的基本版本:

import styles from "../styles/Home.module.css";
import Link from "next/link";
import { useRouter } from "next/router";
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  useQuery,
  gql,
} from "@apollo/client";


export default function Home() {
  const client = new ApolloClient({
    uri: MY_URL,
    cache: new InMemoryCache(),
  });

  const PRODUCTS = gql`
    query {
      products(pageSize: 20, currentPage: 1, filter: {}) {
        items {
          id
          name
        }
        total_count
      }
    }
  `;

  const { loading, error, data } = useQuery(PRODUCTS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return (
    <ApolloProvider client={client}>
      <div className={styles.container}>
        <Head>
          <title>Create Next App</title>
          <link rel="icon" href="/favicon.ico" />
        </Head>

        <main className={styles.main}>
          <a>Escolher: </a>
          <br></br>
          {data.products.map(({ id, name }) => (
            <li key={id}>
                <a>{name}</a>
              <br />
            </li>
          ))}
        </main>
      </div>
    </ApolloProvider>
  );
}

这些是我对 package.json 的唯一依赖项(我认为问题不在这里,但只是为了确定):

    "@apollo/client": "^3.3.13",
    "graphql": "^15.5.0",
    "next": "10.0.9",
    "react": "17.0.1",
    "react-dom": "17.0.1"
  },
  "devDependencies": {
    "@types/node": "^14.14.35",
    "@types/react": "^17.0.3",
    "typescript": "^4.2.3"
  }

我的 JS 代码可以很好地处理硬编码数据,并且 GraphQL 查询也有效。有任何想法吗?谢谢!

【问题讨论】:

  • 问题是您在使用 ApolloProvider 组件渲染组件之前使用 useQuery。您需要在 Home 的父组件中定义您的客户端,或者在子组件中而不是在 Home 中使用 useQuery。

标签: reactjs typescript graphql next.js apollo


【解决方案1】:

按照本教程,我能够从这个错误中继续前进:

https://www.apollographql.com/blog/building-a-next-js-app-with-apollo-client-slash-graphql/

如果不需要后端部分,请忽略它,这就是我所做的。

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 1970-01-01
    • 2020-02-18
    • 2021-04-14
    • 2020-03-13
    • 2021-04-19
    • 2021-07-17
    • 2018-09-25
    • 2018-10-08
    相关资源
    最近更新 更多