P粉9519143812023-09-02 12:24:18
useState
Returns an array containing two elements: a value stored in the state and a function used to update it. If you call const [isOpen, setIsOpen] = useState(null)
, isOpen
is your value (initially set to null
), setIsOpen
is a function used to update it.
When you write const handleToggle = () => { setIsOpen(isOpen() ) }
you are trying to call a null
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 isOpen
, you should declare isOpen
as a boolean and call ## with the opposite value of isOpen
#setIsOpen:
const [isOpen, setIsOpen] = useState(false); // <= 将其最初设置为 false const handleToggle = () => { setIsOpen(!isOpen); // <= 当它为 false 时,将 isOpen 设置为 true,当它为 true 时,将 isOpen 设置为 false };However, if you call
handleToggle in a
useEffect without 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.