I'm trying to convert my class-based component to a function-based component, which I wrote some time while learning REACT, but during the conversion, I got an error that isOpen is not a function, I'm a little confused because I defined it as a state and called it in handleToggle() and then called it at the component's logo.
import React, { useState, useEffect } from "react"; import logo from "../images/logo.svg"; import { FaAlignRight } from "react-icons/fa"; import { Link } from "react-router-dom"; import Badge from '@mui/material/Badge'; import Menu from '@mui/material/Menu'; import MenuItem from '@mui/material/MenuItem'; export default function Navbar(){ const [anchorEl, setAnchorEl] = useState(null); const open = Boolean(anchorEl); const handleClick = (event) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const [isOpen, setIsOpen] = useState(null); useEffect(() =>{ handleToggle(); }); // state = { // isOpen: false, // }; const handleToggle = () => { setIsOpen(isOpen() ); }; return ( ); }
将非常感谢任何建议。
useState
Returns an array containing two elements: a value stored in the state and a function used to update it. If you callconst [isOpen, setIsOpen] = useState(null)
,isOpen
is your value (initially set tonull
),setIsOpen
is a function used to update it.When you write
const handleToggle = () => { setIsOpen(isOpen() ) }
you are trying to call anull
value, which is not possible because It's not a function. This is what the error message tells you.If you want to toggle the value of
However, if you callisOpen
, you should declareisOpen
as a boolean and call ## with the opposite value ofisOpen
#setIsOpen:
handleToggle
in a
useEffectwithout a dependency array, as you are doing, it will be called on every re-render, which may Not what you want. You'll most likely want to call it in response to user interaction - for example in response to an HTML element event such as
onClick. Otherwise, you should refactor your code to add necessary dependencies to
useEffect.