[英]Error: React Hook "useState" is called in function
I updated the navbar on my site that I developed with NextJs and created header and etc.. then I encountered the following build error.我更新了我使用 NextJs 开发的网站上的导航栏,并创建了 header 等。然后我遇到了以下构建错误。
build error message:构建错误信息:
I did some research and tried various things and I solved the part about useEffect by changing the lines, but then I started getting the above errors.我做了一些研究并尝试了各种方法,并通过更改线条解决了有关 useEffect 的部分,但后来我开始遇到上述错误。 When I researched them, I did not come across very useful results.
当我研究它们时,我没有得到非常有用的结果。 Below is the code in the header.jsx file.
下面是 header.jsx 文件中的代码。
import NextLink from "next/link";
import {useEffect, useState } from "react";
import { useRouter } from "next/router";
import cx from "classnames";
import IconArrowDropDown from "./icons/arrow-drop-down";
const MENU = {
"/": "Home",
"/works": "Works",
"/resume": "Resume",
"/post": "Blog",
"/contact": "Contact",
};
const header = () => {
const [isNavOpen, setIsNavOpen] = useState(false);
const router = useRouter();
const { pathname } = useRouter();
const clearSlash = pathname.split("/")[1];
const pathName = clearSlash ? `/${clearSlash}` : "/";
useEffect(() => {
const handleRouteChangeStart = () => {
setIsNavOpen(false);
};
router.events.on("routeChangeStart", handleRouteChangeStart);
return () => {
router.events.off("routeChangeStart", handleRouteChangeStart);
};
}, []);
return (
<header>
<div className="max-w-screen-sm mx-auto flex flex-row justify-between py-6 px-6">
<NextLink href="/">
<a className="text-gray-900 text-xl">
<span className="ml-3 font-bold text-xl">onurhan.dev</span>
</a>
</NextLink>
<nav
className={cx(
isNavOpen ? "flex" : "hidden",
"flex-col gap-x-6 sm:!flex sm:flex-row"
)}
>
{Object.keys(MENU).map((path) => {
const isActive = path === pathName;
return (
<span key={path}>
<NextLink href={path}>
<a className={cx( isActive ? "text-zinc-900" : "text-gray-600" )}>{MENU[path]}</a>
</NextLink>
</span>
);
})}
</nav>
{!isNavOpen && (
<button
type="button"
className="flex bg-zinc-100 text-gray-700 px-3 py-1 rounded-full select-none items-center sm:hidden"
onClick={() => {
setIsNavOpen(true);
}}
>
<span>{MENU[pathName]}</span>
<IconArrowDropDown className="opacity-50" />
</button>
)}
</div>
</header>
);
};
export default header;
Custom components in React should start with block letter. React 中的自定义组件应该以大写字母开头。 Try this:
尝试这个:
const Header = () => {
From the docs:从文档:
Note: Always start component names with a capital letter.
注意:始终以大写字母开头组件名称。
React treats components starting with lowercase letters as DOM tags. React 将以小写字母开头的组件视为 DOM 标签。
I'm not sure about this solution, but maybe try this.我不确定这个解决方案,但也许试试这个。
const [isNavOpen, setIsNavOpen] = useState(false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.