Skip to content

Commit 4582e04

Browse files
authored
fix: Should not crash when item remove by scroll (#90)
1 parent 7bf73e3 commit 4582e04

File tree

4 files changed

+28
-6
lines changed

4 files changed

+28
-6
lines changed

examples/basic.tsx

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,17 @@ const Demo = () => {
8888
>
8989
Scroll To 100px
9090
</button>
91+
<button
92+
type="button"
93+
onClick={() => {
94+
listRef.current.scrollTo({
95+
index: 99999999,
96+
align: 'top',
97+
});
98+
}}
99+
>
100+
Scroll To 99999999 (top)
101+
</button>
91102
<button
92103
type="button"
93104
onClick={() => {

src/List.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
8888
if (typeof itemKey === 'function') {
8989
return itemKey(item);
9090
}
91-
return item[itemKey];
91+
return item?.[itemKey];
9292
},
9393
[itemKey],
9494
);

src/hooks/useScrollTo.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,9 @@ export default function useScrollTo<T>(
5858
let itemTop = 0;
5959
let itemBottom = 0;
6060

61-
for (let i = 0; i <= index; i += 1) {
61+
const maxLen = Math.min(data.length, index);
62+
63+
for (let i = 0; i <= maxLen; i += 1) {
6264
const key = getKey(data[i]);
6365
itemTop = stackTop;
6466
const cacheHeight = heights.get(key);

tests/scroll.test.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,19 @@ describe('List.Scroll', () => {
7777
const listRef = React.createRef();
7878
const wrapper = genList({ itemHeight: 20, height: 100, data: genData(100), ref: listRef });
7979

80-
it('index scroll', () => {
81-
listRef.current.scrollTo({ index: 30, align: 'top' });
82-
jest.runAllTimers();
83-
expect(wrapper.find('ul').instance().scrollTop).toEqual(600);
80+
describe('index scroll', () => {
81+
it('work', () => {
82+
listRef.current.scrollTo({ index: 30, align: 'top' });
83+
jest.runAllTimers();
84+
expect(wrapper.find('ul').instance().scrollTop).toEqual(600);
85+
});
86+
87+
it('out of range should not crash', () => {
88+
expect(() => {
89+
listRef.current.scrollTo({ index: 99999999999, align: 'top' });
90+
jest.runAllTimers();
91+
}).not.toThrow();
92+
});
8493
});
8594

8695
it('scroll top should not out of range', () => {

0 commit comments

Comments
 (0)