网上到处都有很多关于这个问题的帖子,但没有一个解决方案适合我。
我收到错误:
<块引用>不变违规:无法在上下文中找到“客户端”或作为选项传入。将根组件包裹在一个 中,或者通过选项传递一个 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 查询也有效。有任何想法吗?谢谢!
答案 0 :(得分:0)
通过遵循本教程,我能够摆脱这个错误:
https://www.apollographql.com/blog/building-a-next-js-app-with-apollo-client-slash-graphql/
如果您不需要后端部分,请忽略它,这就是我所做的。