我有NextJS应用程序,我在文件的顶部使用"use client"
声明页面是客户端。当我试图构建应用程序时,我得到错误声明
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
ReferenceError: location is not defined
字符串
一个堆栈跟踪指向next.js内部的某个地方,它是构建文件。
其中一个文件中的示例代码如下所示:
"use client";
function classNames(...classes: string[]) {
return classes.filter(Boolean).join(" ");
}
export default function RootTemplate({
children,
}: {
children: React.ReactNode;
}) {
const router = useRouter();
const pathname = usePathname();
const [navigation, setNavigation] = useState<any[]>([]);
const { useSession, signOut } = useContext(AuthContext);
const userNavigation = [
{ name: "Your profile", click: null, href: "/profile" },
{ name: "Sign out", click: signOut },
];
const [sidebarOpen, setSidebarOpen] = useState(false);
const { session: data, status } = useSession();
const username = data?.user?.name;
useEffect(() => {
setNavigation([
{
name: "Dashboard",
href: "/",
icon: HomeIcon,
current: pathname === "/",
},
{
name: "Users",
href: "/users",
icon: UsersIcon,
current: pathname === "/users",
},
{
name: "Organisation",
href: "/organisations",
icon: BuildingOfficeIcon,
current: pathname === "/organisations",
},
{
name: "Connection",
href: "/connections",
icon: LockClosedIcon,
current: pathname === "/connections",
},
]);
}, [pathname]);
if (status === "unauthenticated" && typeof location !== "undefined") {
if (!(pathname === "/login" || pathname === "/register")) {
router.push("/login");
return (
<>
<Loading />
</>
);
} else {
return <>{children}</>;
}
}
型
我所期望的是,页面将作为HTML构建,并且不会尝试在服务器上预渲染,因为我在文件顶部使用"use client"
指令。同时,似乎nextjs正在尝试按原样预渲染页面,并且因为来自NextJS的usePathname
钩子使用window.location
,所以它无法构建。
我通过检查location
在预渲染时唯一的默认状态status
中是否未定义来解决这个问题。
1条答案
按热度按时间yvgpqqbh1#
处理这个问题的一种方法是有条件地只在
usePathname
可用时使用它,比如:字符串