Skip to content

Commit 143fca7

Browse files
committed
fix: Virtual switch makes shake
1 parent 3e8a810 commit 143fca7

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed

examples/switch.tsx

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import * as React from 'react';
2+
import List from '../src/List';
3+
4+
interface Item {
5+
id: number;
6+
}
7+
8+
const MyItem: React.FC<Item> = ({ id }, ref) => (
9+
<span
10+
ref={ref}
11+
style={{
12+
border: '1px solid gray',
13+
padding: '0 16px',
14+
height: 30,
15+
lineHeight: '30px',
16+
boxSizing: 'border-box',
17+
display: 'inline-block',
18+
}}
19+
>
20+
{id}
21+
</span>
22+
);
23+
24+
const ForwardMyItem = React.forwardRef(MyItem);
25+
26+
function getData(count: number) {
27+
const data: Item[] = [];
28+
for (let i = 0; i < count; i += 1) {
29+
data.push({
30+
id: i,
31+
});
32+
}
33+
return data;
34+
}
35+
36+
const Demo = () => {
37+
const [data, setData] = React.useState<{ id: number }[]>(getData(1));
38+
39+
return (
40+
<React.StrictMode>
41+
<div>
42+
<h2>Switch</h2>
43+
<List
44+
data={data}
45+
height={200}
46+
itemHeight={30}
47+
itemKey="id"
48+
style={{
49+
border: '1px solid red',
50+
boxSizing: 'border-box',
51+
}}
52+
>
53+
{(item, _, props) => <ForwardMyItem {...item} {...props} />}
54+
</List>
55+
<button
56+
type="button"
57+
onClick={() => {
58+
setData(data.length === 1 ? getData(10000) : getData(1));
59+
}}
60+
>
61+
Switch
62+
</button>
63+
</div>
64+
</React.StrictMode>
65+
);
66+
};
67+
68+
export default Demo;

src/List.tsx

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,12 @@ class List<T> extends React.Component<ListProps<T>, ListState<T>> {
576576

577577
// Render pure list if not set height or height is enough for all items
578578
if (!isVirtual) {
579+
/**
580+
* Virtual list switch is works on component updated.
581+
* We should double check here if need cut the content.
582+
*/
583+
const shouldVirtual = requireVirtual(height, itemHeight, data.length);
584+
579585
return (
580586
<Component
581587
style={height ? { ...style, height, ...ScrollStyle } : style}
@@ -585,7 +591,11 @@ class List<T> extends React.Component<ListProps<T>, ListState<T>> {
585591
ref={this.listRef}
586592
>
587593
<Filler prefixCls={prefixCls} height={height}>
588-
{this.renderChildren(data, 0, children)}
594+
{this.renderChildren(
595+
shouldVirtual ? data.slice(0, Math.ceil(height / itemHeight)) : data,
596+
0,
597+
children,
598+
)}
589599
</Filler>
590600
</Component>
591601
);

0 commit comments

Comments
 (0)