useQueryWithStore正常工作但useGetList无法获取数据的问题
React-admin 3.14中useGetList钩子无法获取数据的问题
问题描述
我原本通过useQueryWithStore钩子正常从数据提供者获取条目列表:
const { data, total, loading, loaded, error, refetch } = useQueryWithStore({ type: 'getList', resource: 'client/account', payload: { pagination: { page: page + 1, perPage: rowsPerPage, }, sort: { order: sortOrder, field: sortBy, }, }, }) if (!loaded) { return <Loading /> } if (error) { return <p>ERROR</p> } // 渲染数据
切换到专用钩子useGetList后,API能正常返回数据,但解构出的字段均无有效数据:
const { data, total, ids, loading, loaded, error, refetch } = useGetList<ClientAccount>( 'client/account', { page: page + 1, perPage: rowsPerPage, }, { order: sortOrder, field: sortBy, } ) if (loading) { return <Loading /> } if (error) { return <p>ERROR</p> } // 渲染数据
异常现象
total为 undefineddata是空对象ids是空数组loaded为 trueloading为 false
通过Redux DevTools检查,已正常调度CUSTOM_QUERY_SUCCESS动作,且能看到返回的data数组,但钩子解构结果仍无数据。同时发现项目使用的是node_modules/ra-core/esm/dataProvider/useGetList.js,而源码目录下还有useGetList.ts文件,两者的区别是什么?
问题分析与解决
1. 参数传递缺失导致的错位
React-admin 3.x版本的useGetList钩子签名为:
useGetList( resource: string, pagination: PaginationPayload, sort: SortPayload, filter: FilterPayload, options?: UseGetListOptions )
你当前的调用省略了filter参数,即使不需要过滤条件,也必须传递一个空对象{}作为第四个参数,否则会导致内部参数处理逻辑出错:
const { data, total, ids, loading, loaded, error, refetch } = useGetList<ClientAccount>( 'client/account', { page: page + 1, perPage: rowsPerPage }, { order: sortOrder, field: sortBy }, {} // 添加空filter参数 )
2. 数据格式验证
useGetList要求数据提供者返回的结果必须严格符合{ data: T[], total: number }的结构,请确认你的dataProvider在处理GET_LIST请求时,是否正确提取并返回了total值——这是导致total为undefined的常见原因。
另外,确保返回的每条数据都包含id字段(或在react-admin配置中指定了自定义主键),因为useGetList会将数组数据转换为以id为键的对象结构,若缺少主键字段,会导致data为空对象、ids为空数组。
3. ES模块与TS源码的区别
node_modules/ra-core/ra-core/dataProvider/useGetList.ts是TypeScript源码文件,用于开发阶段的类型检查与代码维护;node_modules/ra-core/esm/dataProvider/useGetList.js是编译后的ES模块版本,是项目运行时实际加载执行的代码;
两者逻辑完全一致,仅存在格式与用途的差异,不存在功能区别。
内容的提问来源于stack exchange,提问作者Heikkisorsa
相关产品推荐
相关产品推荐

