2019-05-17 12:05:03 +08:00
|
|
|
---
|
|
|
|
order: 1
|
|
|
|
title:
|
|
|
|
zh-CN: 异步加载
|
|
|
|
en-US: Asynchronous loading
|
|
|
|
---
|
|
|
|
|
|
|
|
## zh-CN
|
|
|
|
|
|
|
|
匹配内容列表为异步返回时。
|
|
|
|
|
|
|
|
## en-US
|
|
|
|
|
|
|
|
async
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
```tsx
|
2019-05-17 12:05:03 +08:00
|
|
|
import { Mentions } from 'antd';
|
|
|
|
import debounce from 'lodash/debounce';
|
2022-05-23 14:37:16 +08:00
|
|
|
import React, { useCallback, useRef, useState } from 'react';
|
2019-05-17 12:05:03 +08:00
|
|
|
|
|
|
|
const { Option } = Mentions;
|
2022-05-19 09:46:26 +08:00
|
|
|
const App: React.FC = () => {
|
2022-05-17 10:19:38 +08:00
|
|
|
const [loading, setLoading] = useState(false);
|
2022-05-19 09:46:26 +08:00
|
|
|
const [users, setUsers] = useState<{ login: string; avatar_url: string }[]>([]);
|
2022-05-20 15:34:02 +08:00
|
|
|
const ref = useRef<string>();
|
2022-05-17 10:19:38 +08:00
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
const loadGithubUsers = (key: string) => {
|
|
|
|
if (!key) {
|
|
|
|
setUsers([]);
|
|
|
|
return;
|
|
|
|
}
|
2022-05-17 10:19:38 +08:00
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
fetch(`https://api.github.com/search/users?q=${key}`)
|
|
|
|
.then(res => res.json())
|
|
|
|
.then(({ items = [] }) => {
|
2022-05-20 15:34:02 +08:00
|
|
|
if (ref.current !== key) return;
|
2022-05-19 09:46:26 +08:00
|
|
|
|
|
|
|
setLoading(false);
|
|
|
|
setUsers(items.slice(0, 10));
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2022-05-20 15:34:02 +08:00
|
|
|
const debounceLoadGithubUsers = useCallback(debounce(loadGithubUsers, 800), []);
|
2022-05-17 10:19:38 +08:00
|
|
|
|
2022-05-20 15:34:02 +08:00
|
|
|
const onSearch = (search: string) => {
|
|
|
|
console.log('Search:', search);
|
|
|
|
ref.current = search;
|
2022-05-17 10:19:38 +08:00
|
|
|
setLoading(!!search);
|
|
|
|
setUsers([]);
|
2022-05-19 09:46:26 +08:00
|
|
|
|
2022-05-20 15:34:02 +08:00
|
|
|
debounceLoadGithubUsers(search);
|
2019-05-17 12:05:03 +08:00
|
|
|
};
|
|
|
|
|
2022-05-17 10:19:38 +08:00
|
|
|
return (
|
|
|
|
<Mentions style={{ width: '100%' }} loading={loading} onSearch={onSearch}>
|
|
|
|
{users.map(({ login, avatar_url: avatar }) => (
|
|
|
|
<Option key={login} value={login} className="antd-demo-dynamic-option">
|
|
|
|
<img src={avatar} alt={login} />
|
|
|
|
<span>{login}</span>
|
|
|
|
</Option>
|
|
|
|
))}
|
|
|
|
</Mentions>
|
|
|
|
);
|
|
|
|
};
|
2022-05-19 09:46:26 +08:00
|
|
|
|
|
|
|
export default App;
|
2019-05-17 12:05:03 +08:00
|
|
|
```
|
|
|
|
|
|
|
|
<style>
|
|
|
|
.antd-demo-dynamic-option img {
|
|
|
|
width: 20px;
|
|
|
|
height: 20px;
|
|
|
|
margin-right: 8px;
|
|
|
|
}
|
|
|
|
</style>
|