【图文并茂】ant design pro 如何统一封装好 ProFormSelect 的查询请求



你仔细看上面的图片吧

经常有这样的需求吧。

这些列表都是查询出来的。

后端

你的后端必须要有 api 。

c 复制代码
const getUsers = handleAsync(async (req: Request, res: Response) => {
  const { email, name, live, current = '1', pageSize = '10' } = req.query;

  const query: any = {};

  if (email) {
    query.email = email;
  }

  if (name) {
    query.name = { $regex: name, $options: 'i' };
  }

  if (live) {
    query.live = live === 'true';
  }

  // 执行查询
  const users = await User.find({
    ...query,
  })
    .populate('roles')
    .sort('-createdAt') // Sort by creation time in descending order
    .skip((+current - 1) * +pageSize)
    .limit(+pageSize)
    .exec();

  const total = await User.countDocuments({
    ...query,
  }).exec();

  res.json({
    success: true,
    data: users.map((user) => exclude(user.toObject(), 'password')),
    total,
    current: +current,
    pageSize: +pageSize,
  });
});

很简单理解,你只要查询好数据库把列表返回就行

至于分页,你可以跳过的,把每页的数量弄大一些传过来就行。后面会提到。

前端

前端只要把 ProFormSelect 组件放上去

c 复制代码
import { ProFormSelect } from '@ant-design/pro-components';
import React from 'react';
import { useIntl } from '@umijs/max';
import useQueryList from '@/hooks/useQueryList';

const UserSelect: React.FC = () => {
  const intl = useIntl();
  const { items: users, loading } = useQueryList('/users');

  const filteredUsers = users.filter(
    (user: any) =>
      user.role !== 'ADMIN' && user.role !== 'ORDER_PLACER' && user.role !== 'REVIEWER',
  );

  return (
    <ProFormSelect
      rules={[{ required: true }]}
      options={filteredUsers.map((user: any) => ({
        label: user.name,
        value: user._id,
      }))}
      width="md"
      name="user"
      label={intl.formatMessage({ id: 'user' })}
      showSearch
      fieldProps={{ loading }}
    />
  );
};

export default UserSelect;

useQueryList

这里有两个东西要注意

第一

c 复制代码
  const { items: users, loading } = useQueryList('/users');

这个地方主要就是发请求了。

这里做了统一封装

src/hooks/useQueryList.ts

c 复制代码
import { useEffect, useState } from 'react';
import { queryList } from '@/services/ant-design-pro/api';

const useQueryList = (url: string, hasPermission = true) => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);

  const query = async () => {
    setLoading(true);
    // Only proceed with the API call if the user has permission
    if (hasPermission) {
      const response = (await queryList(url, { pageSize: 10000 })) as any;
      if (response.success) {
        setItems(response.data);
      }
    }
    setLoading(false);
  };

  useEffect(() => {
    query().catch(console.error);
  }, [hasPermission]); // Adding `hasPermission` to the dependency array to re-run the effect if it changes

  return { items, setItems, loading };
};

export default useQueryList;

loading

fieldProps={{ loading }}

数据没出来前是有个 loading 显示的

跟这里的刚才结合了:

c 复制代码
  const { items: users, loading } = useQueryList('/users');

完结

相关推荐
夜郎king6 分钟前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
辰风沐阳14 分钟前
JavaScript 的宏任务和微任务
javascript
夏幻灵1 小时前
HTML5里最常用的十大标签
前端·html·html5
冰暮流星1 小时前
javascript之二重循环练习
开发语言·javascript·数据库
Mr Xu_1 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
未来龙皇小蓝1 小时前
RBAC前端架构-01:项目初始化
前端·架构
程序员agions2 小时前
2026年,微前端终于“死“了
前端·状态模式
万岳科技系统开发2 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
程序员猫哥_2 小时前
HTML 生成网页工具推荐:从手写代码到 AI 自动生成网页的进化路径
前端·人工智能·html
龙飞052 小时前
Systemd -systemctl - journalctl 速查表:服务管理 + 日志排障
linux·运维·前端·chrome·systemctl·journalctl