1
1
import * as React from 'react' ;
2
- import { useRef } from 'react' ;
2
+ import { useRef , useEffect } from 'react' ;
3
3
import findDOMNode from 'rc-util/lib/Dom/findDOMNode' ;
4
+ import raf from 'rc-util/lib/raf' ;
4
5
import type { GetKey } from '../interface' ;
5
6
import CacheMap from '../utils/CacheMap' ;
6
7
@@ -12,16 +13,16 @@ export default function useHeights<T>(
12
13
const [ updatedMark , setUpdatedMark ] = React . useState ( 0 ) ;
13
14
const instanceRef = useRef ( new Map < React . Key , HTMLElement > ( ) ) ;
14
15
const heightsRef = useRef ( new CacheMap ( ) ) ;
15
- const heightUpdateIdRef = useRef ( 0 ) ;
16
+ const collectRafRef = useRef < number > ( ) ;
16
17
17
- function collectHeight ( ) {
18
- heightUpdateIdRef . current += 1 ;
19
- const currentId = heightUpdateIdRef . current ;
18
+ function cancelRaf ( ) {
19
+ raf . cancel ( collectRafRef . current ) ;
20
+ }
20
21
21
- Promise . resolve ( ) . then ( ( ) => {
22
- // Only collect when it's latest call
23
- if ( currentId !== heightUpdateIdRef . current ) return ;
22
+ function collectHeight ( ) {
23
+ cancelRaf ( ) ;
24
24
25
+ collectRafRef . current = raf ( ( ) => {
25
26
instanceRef . current . forEach ( ( element , key ) => {
26
27
if ( element && element . offsetParent ) {
27
28
const htmlElement = findDOMNode < HTMLElement > ( element ) ;
@@ -33,7 +34,7 @@ export default function useHeights<T>(
33
34
} ) ;
34
35
35
36
// Always trigger update mark to tell parent that should re-calculate heights when resized
36
- setUpdatedMark ( c => c + 1 ) ;
37
+ setUpdatedMark ( ( c ) => c + 1 ) ;
37
38
} ) ;
38
39
}
39
40
@@ -58,5 +59,9 @@ export default function useHeights<T>(
58
59
}
59
60
}
60
61
62
+ useEffect ( ( ) => {
63
+ return cancelRaf ;
64
+ } , [ ] ) ;
65
+
61
66
return [ setInstanceRef , collectHeight , heightsRef . current , updatedMark ] ;
62
67
}
0 commit comments