当前位置: 首页 > news >正文

[React]Antd Select组件输入搜索时调用接口

前言

由于接口返回较多,需要在Select组件中输入时进行调用接口并搜索,而不是初始化时把全部写入Option。

问题

当输入中文时,每打一个字母都会调用一次接口,想在中文输入完成,即点击空格后再进行接口调用

<Selectprefix={<SearchOutlinedstyle={{color: SearchOutlinedColor?.backgroundColor,}}/>}showSearchvalue={orgValue}placeholder={t('Input Search Text')}style={{ width: 250 }}defaultActiveFirstOption={false}suffixIcon={null}filterOption={false}notFoundContent={null}onSearch={handleOrgSearch}onChange={handleOrgChange}options={orgOptions}onCompositionStart={handleCompositionStart}  // 对中文的处理onCompositionEnd={handleCompositionEnd}allowClearonClear={() => {setOrgValue('');onOrgSearch('');setOrgOptions([]);}}size="small"variant="filled"/>

引入lodash.debounce

const [orgValue, setOrgValue] = useState();
const [orgOptions, setOrgOptions] = useState([]);
const [isComposing, setIsComposing] = useState(false);
const searchRef = useRef(null);// 注册debouncedRef,输入结束后再进行接口调用
const debouncedFetchOrgData = useRef(debounce((searchValue) => {fetchOrgList(searchValue, setOrgOptions);}, 500)
).current;// 调用接口,获取列表,放入option中
const fetchOrgList = (value, callback) => {selectCenterInfo({ name: value }).then(result => {if (result.length) {const data = result.map((item) => ({value: item.value,label: `${item.label}(${item.value})`,}));callback(data);} else {callback([]);}}).catch(err => {console.log(err);callback([]);});
};const handleOrgSearch = (newValue) => {searchRef.current = newValue;if (!isComposing) {debouncedFetchOrgData(newValue);};
};const handleOrgChange = (newValue) => {setOrgValue(newValue);onOrgSearch(newValue);  // 这是传入组件的props, 用来把选中的值传回父组件
};const handleCompositionStart = () => {  setIsComposing(true);
};const handleCompositionEnd = (e) => {setIsComposing(false);searchRef.current = e.target.value;if (searchRef.current) {fetchOrgList(searchRef.current, setOrgOptions);}
};useEffect(() => {return () => {debouncedFetchOrgData.cancel();};
}, [debouncedFetchOrgData]);
http://www.xdnf.cn/news/1363393.html

相关文章:

  • 基于RFM模型的客户群体大数据分析及用户聚类系统的设计与实现
  • 【Flink】运行模式
  • 文献阅读笔记:KalmanNet-融合神经网络和卡尔曼滤波的部分已知动力学状态估计
  • Zabbix Vs. Grafana
  • win11中系统的WSL安装Centos以及必要组件
  • nmcli命令详解
  • Docker:网络连接
  • SQL性能调优
  • 2025年8月25日-8月31日(qtopengl+ue独立游戏)
  • 告别“复制粘贴”式换肤:我用Adobe XD组件变体与CC库,构建多品牌设计系统架构
  • THM Bricks Heist靶机
  • 新的 macOS 安装程序声称能够快速窃取数据,并在暗网上销售
  • 文入门Ubuntu:从零到精通的Linux之旅
  • 【ARM】MDK在debug模式下断点的类型
  • 中介者模式及优化
  • 使用EasyExcel根据模板导出文件
  • imx586手册和相机寄存器部分解读
  • 【Springboot】依赖注入方式
  • Linux 离线安装lrzsz(rz、sz上传下载小插件)
  • IntelliJ IDEA 新手入门教程-Java、Web、Maven创建(带图解)
  • 疯狂星期四文案网第49天运营日记
  • 使用现代 <img> 元素实现完美图片效果(2025 深度实战版)
  • 【图像处理基石】基于Real-ESRGAN的实时图像超分辨率技术实现
  • MongoDB vs MySQL:NoSQL 和 SQL 的核心区别与适用场景
  • Portswigger靶场之Visible error-based SQL injection通关秘籍
  • ADQ3系列USB 3.2接口版本数字化仪隆重登场
  • 将本地jar包推到远程仓库
  • KeepAlived+Haproxy实现负载均衡(SLB)
  • 集成电路学习:什么是Caffe深度学习框架
  • 聊聊负载均衡架构