我有 NextJS 应用程序,我使用文件顶部的
"use client"
声明 Pages 为客户端。当我尝试构建所述应用程序时,我收到错误消息
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
是否未定义来解决了这个问题。
usePathname
使用未定义的位置,而 NextJS 钩子应该能够开箱即用地使用这种组件,而不需要我荒谬的解决方法?或者我处理这个问题的方法是错误的?处理此问题的一种方法可能是仅在可用时有条件地使用
usePathname
,例如:
import { usePathname } from 'your-path-to-usePathname';
let pathname = '/';
if (typeof window !== 'undefined') {
pathname = usePathname();
}
// Use pathname further in your code