Skip to content

Commit 636c04a

Browse files
committed
chore: use promise to enhance scroll logic
1 parent 174c2c1 commit 636c04a

File tree

2 files changed

+13
-8
lines changed

2 files changed

+13
-8
lines changed

src/List.tsx

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -271,10 +271,10 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
271271
rangeRef.current.start = start;
272272
rangeRef.current.end = end;
273273

274+
// When scroll up, first visible item get real height may not same as `itemHeight`,
275+
// Which will make scroll jump.
276+
// Let's sync scroll top to avoid jump
274277
React.useLayoutEffect(() => {
275-
console.log('>>>> offsetTop', offsetTop);
276-
console.log('>>>>', scrollHeight, start, end, heights.getRecord());
277-
278278
const changedRecord = heights.getRecord();
279279
if (changedRecord.size === 1) {
280280
const recordKey = Array.from(changedRecord)[0];
@@ -283,7 +283,6 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
283283
const realStartHeight = heights.get(recordKey);
284284
const diffHeight = realStartHeight - itemHeight;
285285
syncScrollTop((ori) => {
286-
console.log('-->', diffHeight, ori);
287286
return ori + diffHeight;
288287
});
289288
}

src/hooks/useHeights.tsx

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import findDOMNode from 'rc-util/lib/Dom/findDOMNode';
2-
import raf from 'rc-util/lib/raf';
32
import * as React from 'react';
43
import { useEffect, useRef } from 'react';
54
import type { GetKey } from '../interface';
@@ -23,10 +22,11 @@ export default function useHeights<T>(
2322
const [updatedMark, setUpdatedMark] = React.useState(0);
2423
const instanceRef = useRef(new Map<React.Key, HTMLElement>());
2524
const heightsRef = useRef(new CacheMap());
26-
const collectRafRef = useRef<number>();
25+
26+
const promiseIdRef = useRef<number>(0);
2727

2828
function cancelRaf() {
29-
raf.cancel(collectRafRef.current);
29+
promiseIdRef.current += 1;
3030
}
3131

3232
function collectHeight(sync = false) {
@@ -56,7 +56,13 @@ export default function useHeights<T>(
5656
if (sync) {
5757
doCollect();
5858
} else {
59-
collectRafRef.current = raf(doCollect);
59+
promiseIdRef.current += 1;
60+
const id = promiseIdRef.current;
61+
Promise.resolve().then(() => {
62+
if (id === promiseIdRef.current) {
63+
doCollect();
64+
}
65+
});
6066
}
6167
}
6268

0 commit comments

Comments
 (0)