You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJs中location未定义报错,导航current状态设置问题求助

Fix "location is not defined" & Navigation Current State Issues

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 map to create a new array avoids modifying the shared base config, ensuring each page gets its own clean state and eliminating the multiple current: true problem.
  • Client-Side Execution: useEffect runs only after the component mounts in the browser, where window.location is available. For Next.js, router.pathname is safe to use and updates automatically with route changes.
  • Component State: Storing navigation in useState ensures 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 00:02:51