NextJS(AppRouter),Apollo(客户端),在根布局中使用 ApolloProvider 时出错

问题描述 投票:0回答:1

我正在尝试用 Apollo 包装我的整个布局,这样我就可以在我的所有页面中使用 graphQL。

但每当我尝试将 apolloprovider 包装在子组件之外时,它都会显示错误

 ⨯ node_modules\rehackt\rsc.js (36:12) @ throwNoContext
 ⨯ Error: Context is not available in this environment.
    at stringify (<anonymous>)
digest: "1025442082"
null

// apolloClient.js
    import { ApolloClient, InMemoryCache } from "@apollo/client";
    
    let apolloClient;
    
    const getApolloClient = () => {
      if (apolloClient == null){
        apolloClient = new ApolloClient({
          uri: "http://localhost:3000/api/graphql",
          cache: new InMemoryCache(),
        });
      }
      return apolloClient
    };
    
    export default getApolloClient;


// layout.js
import { ApolloProvider } from "@apollo/client";
import getApolloClient from "@/db/apolloClient";

export default async function RootLayout({ children }) {

  const session = await getServerSession();
  const apolloClient = getApolloClient();

  return (
    <html lang="en" suppressHydrationWarning={true}>
      <body className={inter.className}>
      <ApolloProvider client={apolloClient}>
         {children}
      </ApolloProvider>
      </body>
    </html>
  );
}
reactjs next.js graphql apollo
1个回答
0
投票

如果您想将 Apollo Client 与 App Router 一起使用,则必须将其与

@apollo/experimental-nextjs-app-support
库一起使用。

App Router 基于 React Canary 版本,Apollo 客户端无法直接支持该版本,因为它缺少必要的原语 - 因此您需要额外的库。

有关安装和使用说明,请参阅该库的自述文件:https://www.npmjs.com/package/@apollo/experimental-nextjs-app-support

© www.soinside.com 2019 - 2024. All rights reserved.