Title rewritten to: TypeError: isOpen is not a callable function
P粉642920522
P粉642920522 2023-09-01 16:14:48
0
1
465

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 (  ); }

将非常感谢任何建议。

P粉642920522
P粉642920522

reply all (1)
P粉951914381

useStateReturns 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),isOpenis your value (initially set tonull),setIsOpenis a function used to update it.

When you writeconst handleToggle = () => { setIsOpen(isOpen() ) }you are trying to call anullvalue, 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 ofisOpen, you should declareisOpenas a boolean and call ## with the opposite value ofisOpen#setIsOpen

const [isOpen, setIsOpen] = useState(false); // <= 将其最初设置为 false const handleToggle = () => { setIsOpen(!isOpen); // <= 当它为 false 时,将 isOpen 设置为 true,当它为 true 时,将 isOpen 设置为 false };
However, if you call

handleTogglein auseEffectwithout 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 asonClick. Otherwise, you should refactor your code to add necessary dependencies touseEffect.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!