新聞中心
usePersistFn
usePersistFn可以持久化function,保證函數(shù)地址永遠(yuǎn)不會(huì)變化。

成都創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站建設(shè)、做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的遜克網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
import { useRef } from 'react';
export type noop = (...args: any[]) => any;
function usePersistFn(fn: T) {
const fnRef = useRef(fn);
// 每次渲染fn的最新值都會(huì)記錄在fnRef中
fnRef.current = fn;
const persistFn = useRef();
// 初次渲染時(shí)給persistFn賦值,此后persistFn不會(huì)更新
if (!persistFn.current) {
persistFn.current = function (...args) {
return fnRef.current!.apply(this, args);
} as T;
}
// 返回persistFn,感嘆號表示返回值類型非null或undefined,因?yàn)槌醮武秩緯r(shí)persistFn就被賦值為了函數(shù)
return persistFn.current!;
}
export default usePersistFn;
為什么要用usePersistFn?
在React官方文檔中提到
在某些場景中,你可能會(huì)需要用 useCallback 記住一個(gè)回調(diào),但由于內(nèi)部函數(shù)必須經(jīng)常重新創(chuàng)建,記憶效果不是很好,導(dǎo)致子組件重復(fù) render。對于超級復(fù)雜的子組件,重新渲染會(huì)對性能造成影響。通過 usePersistFn,可以保證函數(shù)地址永遠(yuǎn)不會(huì)變化。
官方給出的demo如下
function Form() {
const [text, updateText] = useState('');
const textRef = useRef();
useEffect(() => {
textRef.current = text; // 把它寫入 ref
});
const handleSubmit = useCallback(() => {
const currentText = textRef.current; // 從 ref 讀取它
alert(currentText);
}, [textRef]); // 不要像 [text] 那樣重新創(chuàng)建 handleSubmit
return (
<>
updateText(e.target.value)} />
>
);
}
復(fù)制代碼
ExpensiveTree是一個(gè)復(fù)雜的子組件,其接受一個(gè)props handleSubmit函數(shù)。如果使用useCallback,由于handleSubmit函數(shù)內(nèi)部使用了text變量,便要寫為如下形式:
const handleSubmit = useCallback(() => {
alert(text);
}, [text]);
復(fù)制代碼
只要text發(fā)生變化,useCallback接收的內(nèi)部函數(shù)便要重新創(chuàng)建,導(dǎo)致handleSubmit函數(shù)的引用地址發(fā)生變化。進(jìn)而引起子組件ExpensiveTree的重渲染,對性能產(chǎn)生影響。
usePersistFn的目標(biāo)便是持久化接收的函數(shù),且調(diào)用時(shí)內(nèi)部函數(shù)引用的變量(上例為text)能獲取到實(shí)時(shí)的值(useCallback的依賴傳空數(shù)組也能實(shí)現(xiàn)持久化函數(shù),但無法獲取實(shí)時(shí)的值)
官方給的demo中更新textRef寫在了useEffect中,為什么usePersistFn不這樣實(shí)現(xiàn)?
如果在子組件的useEffect回調(diào)函數(shù)中調(diào)用usePersistFn就會(huì)出現(xiàn)問題。因?yàn)殇秩緯r(shí)會(huì)先執(zhí)行子組件的useEffect,后執(zhí)行父組件自定義hooks的useEffect。
文章出自:??前端餐廳ReTech??,如有轉(zhuǎn)載本文請聯(lián)系前端餐廳ReTech今日頭條號。
github:??https://github.com/zuopf769??
分享名稱:Ahooks源碼分析之usePersistFn
URL分享:http://www.dlmjj.cn/article/cogessh.html


咨詢
建站咨詢
