一、单个模糊查询
对于单个模糊匹配,代码如下:
const [list, setList] = useState([]); //最后显示的option数据
import { map,debounce } from 'lodash-es';
const requestList = useCallback(async params => {
try {
//接口调取函数
const { data } = await fetchCreateSource(params);
setList(data.data);
} catch (e) {
message.error(e.message || '创建来源获取出错!');
}
}, []);
// 查询函数-> antd的查询函数
const handleSearch = debounce(value => {
if (value) {
requestList(value);
} else {
setList([]);
}
}, 500);
html代码如下:
<Col span={4}>
<Form.Item label="xxx" name="xxxxx">
<Select
showSearch
defaultActiveFirstOption={false}
showArrow={false}
filterOption={false}
onSearch={handleSearch}
notFoundContent={null}
placeholder="请输入"
>
{map(list, item => (
<Option value={item.value} key={item.value}>
{item.value}
</Option>
))}
</Select>
</Form.Item>
</Col>
二、多个模糊查询
(1)封装hooks
import { useState } from 'react';
import { debounce } from 'lodash-es';
import { post } from 'src/services/http';
//多个查询的url前缀统一的话可以这样写
const url = '/account/fuzzy/match/';
//params 传url,函数要以use开头
export const useFuzzyMatch = (params: string) => {
const [data, setData] = useState([]);
const request = debounce(value => {
if (value.length < 2) {
return;
}
//这里的post和上面的post一样,通过axios封装得到
post(url + params, {
requestData: value,
}).then(res => {
//这个地方的返回值根据自己的接口返回
setData(res.data.data);
});
}, 500);
return {
data,
request,
};
};
(2)页面调用
const list = useFuzzyMatch('xxxx');//xxxx为url前缀
//使用非常简单
<Col span={4}>
<Form.Item label="创建来源" name="createSource">
<Select
showSearch
defaultActiveFirstOption={false}
showArrow={false}
filterOption={false}
onSearch={list.request}
notFoundContent={null}
placeholder="请输入"
>
{map(list.data, item => (
<Option value={item.value} key={item.value}>
{item.value}
</Option>
))}
</Select>
</Form.Item>
</Col>
post请求函数【之前的文章有】
//ResponseReturn
export interface ResponseReturn<T = any> {
success: number;
info: string;
data: T;
}
// post
export async function post<R = any, P = any>(
url: string,
data?: P,
config?: AxiosRequestConfig,
): Promise<ResponseReturn<R>> {
return http.post(url, data, config);
}