首页
/ 解决ant-design/pro-components中Select组件request请求卡loading问题

解决ant-design/pro-components中Select组件request请求卡loading问题

2025-06-13 20:57:14作者:牧宁李

在使用ant-design/pro-components开发时,很多开发者会遇到Select组件通过request属性异步加载数据时页面一直处于loading状态的问题。本文将深入分析该问题的原因,并提供完整的解决方案。

问题现象

当我们在ProTable或ProForm中使用Select组件,并通过request属性异步获取选项数据时,页面会一直显示loading状态,无法正常渲染下拉选项。典型的代码如下:

const columns = [
  {
    title: '仓库',
    dataIndex: 'repository',
    valueType: 'select',
    request: async () => {
      const {data} = await repo_list.runAsync({})
      return data?.map(item => ({
        label: item.name,
        value: item.name 
      })) || [{}]
    }
  }
]

问题原因分析

经过排查,这个问题通常与ahooks库的使用方式有关。在默认情况下,ahooks的请求会自动触发,但当我们将其用于Select组件的request属性时,这种自动触发机制可能会导致请求状态无法正确更新。

解决方案

要解决这个问题,我们需要在使用ahooks进行数据请求时,显式地设置manual: true参数。这告诉ahooks我们需要手动触发请求,而不是自动执行。修改后的代码如下:

const repo_list = useRequest(yourApiFunction, {
  manual: true // 关键配置
});

const columns = [
  {
    title: '仓库',
    dataIndex: 'repository',
    valueType: 'select',
    request: async () => {
      const {data} = await repo_list.runAsync({})
      return data?.map(item => ({
        label: item.name,
        value: item.name 
      })) || []
    }
  }
]

替代方案

如果你不想使用ahooks,也可以直接使用浏览器原生的fetch API:

request: async () => {
  const response = await fetch('http://localhost:8000/api/repo/')
  const data = await response.json()
  return data.map(item => ({
    label: item.name,
    value: item.name
  }))
}

最佳实践建议

  1. 在使用ahooks进行数据请求时,特别是在表单或表格组件中,建议始终设置manual: true
  2. 确保返回的数据格式正确,每个选项必须包含label和value属性
  3. 处理空数据情况时返回空数组[]而不是包含空对象的数组[{}]
  4. 添加适当的错误处理逻辑,避免请求失败导致界面卡死

通过以上方法,可以完美解决Select组件在ant-design/pro-components中因request请求导致的loading状态卡住问题。

登录后查看全文
热门项目推荐
相关项目推荐