RTK迁移RTK Query遇TypeError: 无法读取undefined的map属性
RTK Query迁移时出现TypeError: Cannot read properties of undefined (reading 'map')的解决方法
问题根源
你遇到的报错是因为调用data.map()时data为undefined,主要有三个可能的原因:
- RTK Query的
useCustomersQuery在请求未完成(初始加载、正在请求)时,data默认是undefined,直接调用map会报错。 - 后端返回的数据结构不是直接的数组,而是包裹在某个字段(比如
data)里,导致你拿到的data是一个对象而非数组。 - 请求可能未成功(比如token无效、接口地址错误),导致
data始终为undefined。
具体解决步骤
1. 处理初始加载状态,避免直接调用map
在渲染列表前,先判断data是否存在,或者结合RTK Query提供的状态做条件渲染:
方法一:使用可选链操作符(推荐)
<Tbody> {data?.map((customer) => ( <CustomersTable key={customer.uid} name={`${customer.first_name} ${customer.last_name}`} logo={customer.logo} id={customer.uid} exchange={customer.exchange} createdAt={moment(customer.createdAt).format('LLL')} /> ))} </Tbody>
方法二:结合状态做条件渲染
// 先处理加载和错误状态 if (isLoading) return <div>加载中...</div>; if (error) return <div>加载失败:{(error as Error).message}</div>; // 确认data存在后再渲染 return ( <Tbody> {data.map((customer) => ( <CustomersTable key={customer.uid} name={`${customer.first_name} ${customer.last_name}`} logo={customer.logo} id={customer.uid} exchange={customer.exchange} createdAt={moment(customer.createdAt).format('LLL')} /> ))} </Tbody> );
2. 检查并适配后端返回的数据结构
打开浏览器开发者工具的Network面板,查看/api/v1/customer/paginate-customer接口的返回内容:
- 如果返回的是类似
{ "data": [/* 客户数组 */] }的结构,需要在API定义中添加transformResponse来提取数组:
endpoints: (builder) => ({ customers: builder.query({ query: () => '/api/v1/customer/paginate-customer', // 提取后端返回中的data字段作为最终的data值 transformResponse: (response) => response.data }) })
3. 验证请求是否正常发送
- 检查Network面板中请求的状态码:如果是401(未授权),说明token未正确携带,需要确认
getState().auth.user.token是否有值。 - 确认接口地址是否正确,后端服务是否正常运行。
内容的提问来源于stack exchange,提问作者user21543876
相关产品推荐
相关产品推荐

