2021-12-03 23:54:19 +08:00
|
|
|
---
|
|
|
|
order: 7
|
|
|
|
title:
|
|
|
|
zh-CN: 滚动加载无限长列表
|
|
|
|
en-US: virtual list
|
|
|
|
---
|
|
|
|
|
|
|
|
## zh-CN
|
|
|
|
|
|
|
|
结合 [rc-virtual-list](https://github.com/react-component/virtual-list) 实现滚动加载无限长列表,能够提高数据量大时候长列表的性能。
|
|
|
|
|
|
|
|
## en-US
|
|
|
|
|
|
|
|
An example of infinite & virtualized list via using [rc-virtual-list](https://github.com/react-component/virtual-list).
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
```tsx
|
2022-05-21 22:14:15 +08:00
|
|
|
import { Avatar, List, message } from 'antd';
|
2021-12-03 23:54:19 +08:00
|
|
|
import VirtualList from 'rc-virtual-list';
|
2022-05-21 22:14:15 +08:00
|
|
|
import React, { useEffect, useState } from 'react';
|
2021-12-03 23:54:19 +08:00
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
interface UserItem {
|
|
|
|
email: string;
|
|
|
|
gender: string;
|
|
|
|
name: {
|
|
|
|
first: string;
|
|
|
|
last: string;
|
|
|
|
title: string;
|
|
|
|
};
|
|
|
|
nat: string;
|
|
|
|
picture: {
|
|
|
|
large: string;
|
|
|
|
medium: string;
|
|
|
|
thumbnail: string;
|
|
|
|
};
|
|
|
|
}
|
2021-12-03 23:54:19 +08:00
|
|
|
|
|
|
|
const fakeDataUrl =
|
|
|
|
'https://randomuser.me/api/?results=20&inc=name,gender,email,nat,picture&noinfo';
|
|
|
|
const ContainerHeight = 400;
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
const App: React.FC = () => {
|
|
|
|
const [data, setData] = useState<UserItem[]>([]);
|
2021-12-03 23:54:19 +08:00
|
|
|
|
|
|
|
const appendData = () => {
|
|
|
|
fetch(fakeDataUrl)
|
|
|
|
.then(res => res.json())
|
|
|
|
.then(body => {
|
|
|
|
setData(data.concat(body.results));
|
|
|
|
message.success(`${body.results.length} more items loaded!`);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
appendData();
|
|
|
|
}, []);
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
const onScroll = (e: React.UIEvent<HTMLElement, UIEvent>) => {
|
|
|
|
if (e.currentTarget.scrollHeight - e.currentTarget.scrollTop === ContainerHeight) {
|
2021-12-03 23:54:19 +08:00
|
|
|
appendData();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<List>
|
|
|
|
<VirtualList
|
|
|
|
data={data}
|
|
|
|
height={ContainerHeight}
|
|
|
|
itemHeight={47}
|
|
|
|
itemKey="email"
|
|
|
|
onScroll={onScroll}
|
|
|
|
>
|
2022-05-19 09:46:26 +08:00
|
|
|
{(item: UserItem) => (
|
2021-12-03 23:54:19 +08:00
|
|
|
<List.Item key={item.email}>
|
|
|
|
<List.Item.Meta
|
|
|
|
avatar={<Avatar src={item.picture.large} />}
|
|
|
|
title={<a href="https://ant.design">{item.name.last}</a>}
|
|
|
|
description={item.email}
|
|
|
|
/>
|
|
|
|
<div>Content</div>
|
|
|
|
</List.Item>
|
|
|
|
)}
|
|
|
|
</VirtualList>
|
|
|
|
</List>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
export default App;
|
2021-12-03 23:54:19 +08:00
|
|
|
```
|