ReactJs中location未定义报错,导航current状态设置问题求助
The error occurs because your code runs on the server during SSR (Server-Side Rendering) when deployed to Vercel. The location object is a browser-only API—there's no window context on the server, hence the "not defined" error. Local development likely uses client-side rendering only, so location is available there. Here's how to fix both the error and the multiple current: true issue:
Solution 1: React/Next.js Client-Side State Update
Wrap your navigation logic in a useEffect hook to run it only after the component mounts (client-side), and create a new array instead of mutating the original to avoid cross-page state leakage:
import { useEffect, useState } from 'react'; // Immutable base navigation config const baseNavigation = [ { name: "Dashboard", href: "/dashboard", current: false }, { name: "Team", href: "/dashboard/team", current: false }, { name: "Projects", href: "/dashboard/projects", current: false }, { name: "Applications", href: "/dashboard/applications", current: false }, { name: "Reports", href: "/dashboard/reports", current: false }, ]; export default function Navigation() { const [navigation, setNavigation] = useState(baseNavigation); useEffect(() => { // Only execute on client where window exists const updatedNav = baseNavigation.map(item => ({ ...item, current: item.href === window.location.pathname })); setNavigation(updatedNav); }, []); return ( <nav> {navigation.map(item => ( <a key={item.href} href={item.href} className={item.current ? 'bg-gray-100' : ''} // Example active class > {item.name} </a> ))} </nav> ); }
Solution 2: Next.js-Specific Fix with useRouter
If you're using Next.js, use useRouter instead of window.location—it handles route changes automatically and works reliably in SSR/SSG environments:
import { useEffect, useState } from 'react'; import { useRouter } from 'next/router'; const baseNavigation = [ { name: "Dashboard", href: "/dashboard", current: false }, { name: "Team", href: "/dashboard/team", current: false }, { name: "Projects", href: "/dashboard/projects", current: false }, { name: "Applications", href: "/dashboard/applications", current: false }, { name: "Reports", href: "/dashboard/reports", current: false }, ]; export default function Navigation() { const router = useRouter(); const [navigation, setNavigation] = useState(baseNavigation); useEffect(() => { const updatedNav = baseNavigation.map(item => ({ ...item, current: item.href === router.pathname })); setNavigation(updatedNav); }, [router.pathname]); // Re-run when route changes return ( <nav> {navigation.map(item => ( <a key={item.href} href={item.href} className={item.current ? 'bg-gray-100' : ''} > {item.name} </a> ))} </nav> ); }
Why These Fixes Work
- No Mutation: Using
mapto create a new array avoids modifying the shared base config, ensuring each page gets its own clean state and eliminating the multiplecurrent: trueproblem. - Client-Side Execution:
useEffectruns only after the component mounts in the browser, wherewindow.locationis available. For Next.js,router.pathnameis safe to use and updates automatically with route changes. - Component State: Storing navigation in
useStateensures each Navigation component instance manages its own state, preventing cross-page interference.
Vanilla JS Fix (Non-Framework)
If working with plain JavaScript, wrap your code in a window existence check to avoid server-side errors:
let navigation = [ { name: "Dashboard", href: "/dashboard", current: false }, // ... other items ]; if (typeof window !== 'undefined') { navigation = navigation.map(item => ({ ...item, current: item.href === window.location.pathname })); }
内容的提问来源于stack exchange,提问作者Youssef Hussein

