From c1329120ae8a4e146fc82cc574fe5b3b4b797012 Mon Sep 17 00:00:00 2001 From: jin-sir <942725119@qq.com> Date: Sun, 29 Sep 2024 11:24:07 +0800 Subject: [PATCH] fix: using ref to solve closure problems --- src/cookies/index.tsx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cookies/index.tsx b/src/cookies/index.tsx index e62b60114..730a7cbb2 100644 --- a/src/cookies/index.tsx +++ b/src/cookies/index.tsx @@ -28,9 +28,11 @@ const useCookieListener = ( options: ICookieOptions = defaultOptions ) => { const { timeout, immediately } = options; + const isWatchAll = !watchFields.length; const timerRef = useRef(); const currentCookiesRef = useRef(document.cookie); - const isWatchAll = !watchFields.length; + const handlerRef = useRef(); + handlerRef.current = handler; useEffect(() => { timerRef.current = window.setInterval(() => { @@ -54,7 +56,7 @@ const useCookieListener = ( changedFields.push({ key, value: newValue }); } } - changedFields.length && handler({ changedFields, prevCookies, nextCookies }); + changedFields.length && handlerRef.current?.({ changedFields, prevCookies, nextCookies }); }; const compareValue = () => { @@ -62,7 +64,7 @@ const useCookieListener = ( const nextCookies = document.cookie; if (prevCookies !== nextCookies) { isWatchAll - ? handler({ prevCookies, nextCookies }) + ? handlerRef.current?.({ prevCookies, nextCookies }) : handleFieldsChange(prevCookies, nextCookies); currentCookiesRef.current = nextCookies; }