react ant design select 远程搜索,调用接口 显示 加载中,接口调用完毕,要是没有数据,显示暂无数据

javascript 复制代码
import { useState } from 'react';
import { Select, Spin } from 'antd';

const { Option } = Select;

const RemoteSearchSelect = () => {
  const [loading, setLoading] = useState(false);
  const [options, setOptions] = useState([]);

  const fetchData = async (value) => {
    setLoading(true);

    // 模拟调用接口获取数据
    try {
      const response = await fetch(`https://api.example.com/search?q=${value}`);
      const data = await response.json();

      if (data.length > 0) {
        setOptions(data);
      } else {
        setOptions([]);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }

    setLoading(false);
  };

  const handleSearch = (value) => {
    // 远程搜索数据
    fetchData(value);
  };

  return (
    <Select
      showSearch
      onSearch={handleSearch}
      placeholder="搜索"
      notFoundContent={loading ? <Spin size="small" /> : options.length === 0 ? "暂无数据" : null}
    >
      {options.map((option) => (
        <Option key={option.value} value={option.value}>
          {option.label}
        </Option>
      ))}
    </Select>
  );
};

export default RemoteSearchSelect;
相关推荐
GISer_Jing6 分钟前
React中Element、Fiber、createElement和Component关系
前端·react.js·前端框架
折翼的恶魔1 小时前
前端学习之样式设计
前端·css·学习
IT_陈寒1 小时前
JavaScript性能优化:3个被低估的V8引擎技巧让你的代码提速50%
前端·人工智能·后端
云飞云共享云桌面2 小时前
SolidWorks服务器多人使用方案
大数据·运维·服务器·前端·网络·电脑·制造
Red Car2 小时前
javascript 性能优化实例一则
开发语言·javascript·ecmascript
艾小码2 小时前
从Hello World到变量数据类型:JavaScript新手避坑指南
前端·javascript
街尾杂货店&3 小时前
css word-spacing属性
前端·css
千叶寻-3 小时前
正则表达式
前端·javascript·后端·架构·正则表达式·node.js
光影少年8 小时前
angular生态及学习路线
前端·学习·angular.js
記億揺晃着的那天10 小时前
Vue + Element UI 表格自适应高度如何做?
javascript·vue.js·ui