以下示例取自usehooks-ts網站
import { useCallback, useEffect, useRef } from 'react'
function useIsMounted() {
const isMounted = useRef(false)
useEffect(() => {
isMounted.current = true
return () => {
isMounted.current = false
}
}, [])
return useCallback(() => isMounted.current, [])
}
export default useIsMounted
為什么我們回傳isMounted.current作為回呼而不只回傳值isMounted.current?
什么是isMounted.current作為一個值回傳將是一個壞主意的例子?
uj5u.com熱心網友回復:
您可以自己測驗不同的實作,看看會發生什么:
const UnmountingChild = ({ unmount }) => {
const { isMounted, isMountedNC } = useIsMounted();
useEffect(() => {
console.log('IS MOUNTED BEFORE FETCH', isMounted()); // true
console.log('IS MOUNTED NO CALLBACK BEFORE FETCH', isMountedNC.current); //true
fetch('https://jsonplaceholder.typicode.com/todos/1').then((d) => {
console.log('IS MOUNTED', isMounted()); //false
console.log('IS MOUNTED NO CALLBACK', isMountedNC.current); //false
});
unmount(); // <-- This triggers the unmount of the component
}, []);
return <>Child</>;
};
function useIsMounted() {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => (isMounted.current = false);
}, []);
return {
isMounted: useCallback(() => isMounted.current, []),
isMountedNC: isMounted,
};
}
在這里查看演示
回呼的使用很有用,因為它允許您在需要時直接讀取refwith的值ref.current,只需呼叫即可isMounted(),如果您想直接回傳 theref您只需要確保回傳所有的ref而不是僅僅ref.current因為如果您通過ref.current您將只傳遞實際值,而不是mutable ref object因此它的值將始終固定在false. 回傳ref強制你每次讀取.current屬性時,這不是很好,它可能會誤導人們在不知道內部實作的情況下使用鉤子,而呼叫isMounted()更好地閱讀和使用并避免使用麻煩。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465474.html
標籤:javascript 反应 反应钩子 使用参考 反应使用回调
