React Antd Select组件输入搜索时调用接口方式
作者:水果摊见
为优化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]);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
