Skip to content

Commit 8826578

Browse files
refactor(use-spring-visibility): 使用useCallback记忆化,保持引用稳定,使用useRef追踪最新值
1 parent 20d84de commit 8826578

1 file changed

Lines changed: 8 additions & 5 deletions

File tree

src/utils/use-spring-visibility.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { useIsomorphicLayoutEffect } from 'ahooks'
22
import type { RefObject } from 'react'
3-
import { useEffect, useRef } from 'react'
3+
import { useCallback, useEffect, useRef } from 'react'
44

55
export function useSpringVisibility({
66
visible,
@@ -28,25 +28,28 @@ export function useSpringVisibility({
2828
}
2929
}, [visible])
3030

31+
const visibleRef = useRef(visible)
32+
visibleRef.current = visible
33+
3134
useEffect(() => {
3235
const handler = () => {
3336
if (document.visibilityState !== 'visible') return
3437
if (unmountedRef.current) return
35-
if (!visible && activeRef.current && !closedRef.current) {
38+
if (!visibleRef.current && activeRef.current && !closedRef.current) {
3639
closedRef.current = true
3740
setActive(false)
3841
afterCloseRef.current?.()
3942
}
4043
}
4144
document.addEventListener('visibilitychange', handler)
4245
return () => document.removeEventListener('visibilitychange', handler)
43-
}, [visible, setActive, unmountedRef])
46+
}, [setActive, unmountedRef])
4447

45-
function shouldCallAfterClose(): boolean {
48+
const shouldCallAfterClose = useCallback((): boolean => {
4649
if (closedRef.current) return false
4750
closedRef.current = true
4851
return true
49-
}
52+
}, [])
5053

5154
return { shouldCallAfterClose }
5255
}

0 commit comments

Comments
 (0)