NodeJS 位置未定义ReactJs

qyswt5oh  于 2023-10-17  发布在  Node.js
关注(0)|答案(2)|浏览(120)

我正试图创建此更改当前的状态,同时加入页面。

const navigation = \[
{ 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 },
\];


for (let i = 0; i \< navigation.length; i++) {
if (navigation\[i\].href === location.pathname) {
navigation\[i\].current = true;
}
}

This is the error i got
我试着用if条件来实现它,但代码太乱了,我试着在每个页面中包含导航数组,并从每个页面更改对象,但它搞砸了,有两个页面的当前状态同时为true::注意:代码是正确的,但当我尝试在Vercel中部署它以与某些人一起测试时,它给了我错误

m1m5dgzv

m1m5dgzv1#

你使用的是nextjs,这意味着第一次渲染将发生在服务器上,而不是浏览器上,所以位置和其他浏览器特定的全局变量,如(window,localStorge)将为null,修复方法是让你的代码在浏览器上运行,以便将你的代码 Package 在useEffect中

useEffect(() => {
    for (let i = 0; i \< navigation.length; i++) {
        if (navigation\[i\].href === location.pathname) {
            navigation\[i\].current = true;
        }
    }   
}, [])
dfty9e19

dfty9e192#

NextJs13
如果你想突出显示活动的导航项,使用如下自定义组件:

'use client';

/*
  NavLink: The "active" class is added when the href matches the start of the URL pathname,
  use the "exact" property to change it to an exact match with the whole URL pathname.
  https://github.com/dstroot/nextjs-13-example/blob/master/components/NavBar/navlink.tsx
*/

import Link, { LinkProps } from 'next/link';
import { usePathname } from 'next/navigation';
import { FC, HTMLProps, RefAttributes } from 'react';
import cn from 'classnames';

export type NavLinkProps = {
  exact?: boolean;
  children?: React.ReactNode;
} & LinkProps &
  HTMLProps<HTMLAnchorElement> &
  RefAttributes<HTMLAnchorElement>;

export const NavLink: FC<NavLinkProps> = ({ exact, children, className, ...props }) => {
  const pathname = usePathname();
  const isActive = exact ? pathname === props.href : pathname?.startsWith(props.href);

  return (
    <Link className={cn(className, { ['link-active']: isActive })} {...props}>
      {children}
    </Link>
  );
};

相关问题