目录引言🦌来看看效果🐿源码实现🐬完整demo源码🍓参考引言 useUnmount,组件卸载时执行的 Hook,比如组件卸载时,需要清除定时器或者相关的监听,就可以使用useUnmou
useUnmount,组件卸载时执行的 Hook,比如组件卸载时,需要清除定时器或者相关的监听,就可以使用useUnmount。
可以看到,只有在子组件销毁时时,useUnmount才执行了。
const useUnmount = (fn: () => void) => {
const fnRef = useRef(fn);
fnRef.current = fn;
useEffect(() => () => fn?.(), []);
};
import { useEffect, useRef, useState } from "React";
// 自定义useUnmount hooks
const useUnmount = (fn: () => void) => {
const fnRef = useRef(fn);
fnRef.current = fn;
useEffect(() => () => fn?.(), []);
};
const Child = () => {
useUnmount(() => {
console.log("子组件销毁了");
});
return <div>我是子组件</div>;
};
const UseUnmountDemo = () => {
const [showChild, setShowChild] = useState(true);
return (
<>
{showChild && <Child />}
<button onClick={() => setShowChild(!showChild)}>显示销毁子组件</button>;
</>
);
};
export default UseUnmountDemo;
有兴趣的小伙伴可以去看,react-use 和 ahooks 的源码,学习前辈们优雅的代码
以上就是每天一个hooks学习之useUnmount的详细内容,更多关于hooks useUnmount的资料请关注编程网其它相关文章!
--结束END--
本文标题: 每天一个hooks学习之useUnmount
本文链接: https://www.lsjlt.com/news/213165.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0