ant-design/components/mentions/demo/async.md
dingkang 196a4351e3
docs: replace class component with hooks (#35580)
* docs(badge): replace class component with hooks

* docs(button): replace class component with hooks

* docs(calendar): replace class component with hooks

* docs(card): replace class component with hooks

* docs(button): replace class component with hooks

* chore(deps): remove webpack devDependencies

* docs(cascader): replace class component with hooks

* docs(checkbox): replace class component with hooks

* docs(collapse): replace class component with hooks

* docs(comment): replace class component with hooks

* docs(descriptions): replace class component with hooks

* docs(config-provider): replace class component with hooks

* docs(date-picker): replace class component with hooks

* docs(drawer): replace class component with hooks

* docs(dropdown): replace class component with hooks

* docs(dropdown): replace class component with hooks

* docs(empty): replace class component with hooks

* docs(grid): replace class component with hooks

* docs(input): replace class component with hooks

* docs(input-number): replace class component with hooks

* docs(demo): fix lint error

* docs(layout): replace class component with hooks

* docs(list): replace class component with hooks

* docs(mentions): replace class component with hooks

* docs: fix code review issue
2022-05-17 10:19:38 +08:00

1.5 KiB

order title
1
zh-CN en-US
异步加载 Asynchronous loading

zh-CN

匹配内容列表为异步返回时。

en-US

async

import React, { useState, useRef, useMemo } from 'react';
import { Mentions } from 'antd';
import debounce from 'lodash/debounce';

const { Option } = Mentions;

export default () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState([]);
  const searchRef = useRef();

  const loadGithubUsers = useMemo(
    () =>
      debounce(key => {
        if (!key) {
          setUsers([]);
          return;
        }

        fetch(`https://api.github.com/search/users?q=${key}`)
          .then(res => res.json())
          .then(({ items = [] }) => {
            if (searchRef.current !== key) return;
            setLoading(false);
            setUsers(items.slice(0, 10));
          });
      }, 800),
    [],
  );

  const onSearch = search => {
    setLoading(!!search);
    setUsers([]);
    searchRef.current = search;
    console.log('Search:', search);
    loadGithubUsers(search);
  };

  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>
  );
};