欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

每天一個(gè)hooks學(xué)習(xí)之useUnmount

 更新時(shí)間:2023年05月09日 09:26:12   作者:jimmy_fx  
這篇文章主要為大家介紹了每天一個(gè)hooks學(xué)習(xí)之useUnmount,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

引言

useUnmount,組件卸載時(shí)執(zhí)行的 Hook,比如組件卸載時(shí),需要清除定時(shí)器或者相關(guān)的監(jiān)聽(tīng),就可以使用useUnmount。

??來(lái)看看效果

可以看到,只有在子組件銷毀時(shí)時(shí),useUnmount才執(zhí)行了。

??源碼實(shí)現(xiàn)

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 的源碼,學(xué)習(xí)前輩們優(yōu)雅的代碼

以上就是每天一個(gè)hooks學(xué)習(xí)之useUnmount的詳細(xì)內(nèi)容,更多關(guān)于hooks useUnmount的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論