React Antd Select组件输入搜索时调用接口方式
更新时间:2025年08月30日 14:23:09 作者:水果摊见
为优化Select组件中文输入时的接口调用,使用lodash.debounce实现防抖,避免每输入一个字母即触发请求,待用户点击空格完成输入后,再调用接口获取数据,提升性能与用户体验
前言
由于接口返回较多,需要在Select组件中输入时进行调用接口并搜索,而不是初始化时把全部写入Option。
问题
当输入中文时,每打一个字母都会调用一次接口,想在中文输入完成,即点击空格后再进行接口调用
<Select
prefix={
<SearchOutlined
style={{
color: SearchOutlinedColor?.backgroundColor,
}}
/>
}
showSearch
value={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}
allowClear
onClear={() => {
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]);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
React Router 5.1.0使用useHistory做页面跳转导航的实现
本文主要介绍了React Router 5.1.0使用useHistory做页面跳转导航的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2021-11-11
使用VSCode Debugger调试React项目的实现步骤
本文主要介绍了使用VSCode Debugger调试React项目的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2025-09-09
详解如何给React-Router添加路由页面切换时的过渡动画
这篇文章主要介绍了详解如何给React-Router添加路由页面切换时的过渡动画,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-04-04


最新评论