React之通过hooks实现模糊查询

一、单个模糊查询

对于单个模糊匹配,代码如下:

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);
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值