以下为ChatGPT自动生成的解答,正确与否请自行判断。 也许你也可以从大家的发帖中找到想要的答案!
BFE.devAI解答 - React 代码题
14. implement useIsMounted()
Here's an implementation of useIsMounted()
using the useState
hook:
import { useState, useEffect } from 'react';
function useIsMounted() {
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
setIsMounted(true);
// The useEffect function returned here is called when the component is unmounting
return () => setIsMounted(false);
}, []);
return isMounted;
}
The useState
hook initializes a isMounted
state variable to false
.
The useEffect
hook is called with an empty array as the second argument, which means it will only be called once, when the component mounts.
The effect function sets the isMounted
state variable to true
.
We also return a cleanup function, which sets the isMounted
state variable to false
when the component unmounts.
The hook returns the isMounted
state variable, which is true
when the component is mounted and false
otherwise.