每天一个hooks学习之useUnmount

 更新时间:2023年05月09日 09:26:12   作者:jimmy_fx  
这篇文章主要为大家介绍了每天一个hooks学习之useUnmount,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

引言

useUnmount,组件卸载时执行的 Hook,比如组件卸载时,需要清除定时器或者相关的监听,就可以使用useUnmount。

🦌来看看效果

可以看到,只有在子组件销毁时时,useUnmount才执行了。

🐿源码实现

const useUnmount = (fn: () => void) => {
  const fnRef = useRef(fn);
  fnRef.current = fn;
  useEffect(() => () => fn?.(), []);
};

🐬完整demo源码

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-useahooks 的源码,学习前辈们优雅的代码

以上就是每天一个hooks学习之useUnmount的详细内容,更多关于hooks useUnmount的资料请关注脚本之家其它相关文章!

相关文章

最新评论