react hook 实现use-watch
作者:互联网
import { useEffect, useRef } from 'react'; const defaultCompare = (prev, next) => prev === next; export const useWatch = ( callback, value, { initialValue = '', compare = defaultCompare } = {}, ) => { const prevValue = useRef(initialValue); const safeEffects = useRef([]); const prev = prevValue.current; if (!compare(prev, value)) { const safeEffect = callback === null || callback === void 0 ? void 0 : callback(prev); if (typeof safeEffect === 'function') { safeEffects.current.push(safeEffect); } prevValue.current = value; } useEffect(() => { safeEffects.current.forEach((safeEffect) => safeEffect()); safeEffects.current = []; }); }; export default useWatch;
标签:current,use,const,callback,safeEffect,react,hook,safeEffects,prev 来源: https://www.cnblogs.com/ygunoil/p/16479186.html