所以问题是我想在进入网站/用户/1等用户页面时查询用户信息 但是当我想进入页面时,我收到错误,我认为它来自阿波罗,所以有办法解决这个问题吗?我做错了什么?
apollo.ts:
"use client";
import { ApolloClient, InMemoryCache } from "@apollo/client";
const createApolloClient = () => {
return new ApolloClient({
uri: "http://localhost:8000/",
cache: new InMemoryCache(),
});
};
export default createApolloClient;
layouts.tsx:
import "./globals.css";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { ApolloProvider } from "@apollo/client";
import createApolloClient from "./apollo";
const inter = Inter({ subsets: ["latin"] });
const client = createApolloClient();
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<ApolloProvider client={client}>
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
</ApolloProvider>
);
}
用户/[用户Id]/page.tsx:
import { useQuery } from "@apollo/client";
import { GET_USER } from "@/graphql/user";
export default function Page({ params }: { params: { userId: string } }) {
const userId = parseInt(params.userId);
if (isNaN(userId)) {
return <h1>user not found</h1>;
}
const { loading, error, data } = useQuery(GET_USER, {
variables: { id: userId },
});
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
const { getUser: user } = data;
console.log(user);
return (
<>
<h1>
user: {user.name} {user.surname}
</h1>
<h1>advert:</h1>
{user.adverts.map((advert: any) => (
<li key={advert.id}>
{advert.location}, {advert.price}
</li>
))}
</>
);
}
获取用户查询:
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";
export const GET_USER = gql`
query GetUser($id: Int!) {
getUser(id: $id) {
phone
email
name
surname
adverts {
id
location
price
}
}
}
`;
我在网上搜索了一些信息,但没有找到解决方案
您的布局文件是服务器组件,并且您的
apollo.ts
被标记为客户端文件,因此您无法从布局中调用该 createApolloClient
函数。
在这种情况下,这真的很好:如果您要在服务器组件的模块范围内创建类似的客户端,则该客户端将在所有用户之间共享,从而可能泄露秘密数据。
请使用官方的 Next.js Apollo 客户端包,这样可以避免此类错误。