NextJS 13 Error / Error: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it

huangapple go评论118阅读模式
英文:

NextJS 13 Error / Error: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it

问题

错误:createContext仅在客户端组件中有效。在文件顶部添加"use client"指令以使用它。

我可以告诉你为什么会发生这个错误吗?

英文:

**Error: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.
**
Can you tell me why the error occurs?

// layout.tsx
import Layout from "./components/common/Layout";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <Layout>{children}</Layout>
      </body>
    </html>
  );
}

// Layout.tsx

"use client";

import React, { useState, ReactNode } from "react";
import Nav from "@app/components/common/Nav";
import { Global, css } from "@emotion/react";
import { PageContextProvider } from "store/pageContext";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

export default function Layout({ children }: { children: ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            refetchOnWindowFocus: false,
            staleTime: 5000,
          },
        },
      })
  );
  return (
    <div>
      <QueryClientProvider client={queryClient}>
        <Global styles={reset} />
        <PageContextProvider>
          <Nav />
          <div>{children}</div>
        </PageContextProvider>
      </QueryClientProvider>
    </div>
  );
}
// pageContext.tsx

"use client";

import React, { createContext, useState, useRef } from "react";

interface PageContextType {
  currentPage: number;
  setCurrentPage: React.Dispatch<React.SetStateAction<number>>;
  sectionsRef: React.MutableRefObject<(HTMLElement | null)[]>;
}

export const PageContext = createContext<PageContextType>({
  currentPage: 0,
  setCurrentPage: () => {},
  sectionsRef: {} as React.MutableRefObject<(HTMLElement | null)[]>,
});

export const PageContextProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [currentPage, setCurrentPage] = useState<number>(0);
  const sectionsRef = useRef<(HTMLDivElement | null)[]>([]);

  return (
    <PageContext.Provider value={{ currentPage, setCurrentPage, sectionsRef }}>
      {children}
    </PageContext.Provider>
  );
};

I want to use the layout.tsx file as a server component and add metadata, but if I don't use "use client" in the layout file, an error occurs. Do you know anyone?

答案1

得分: 1

你可以将 QueryClient 的初始化移动到一个单独的组件中(该组件将具有 useClient),然后在您的 Layout 组件中导入它,并在那里移除 useClient。这样,您的布局组件将成为一个服务器组件。

英文:

You can move the init of QueryClient into a separate component (which will have use client), import it in your Layout component and remove the use client there.
This way your layout component will be a server component.

huangapple
  • 本文由 发表于 2023年7月3日 16:30:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603079.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定