英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论