开发者问题收集

TypeError:无法读取未定义的属性(读取‘地图’)RTK 查询

2023-04-15
796

我正在尝试将我的项目从 RTK 移植到 RTK Query。它与 Redux 工具包配合得很好,但我的经理希望我改用 RTK 查询。我不太明白为什么这里会出现这个错误。我做错了什么?如果我控制台记录数据,我可以看到数据显示“未定义”

import { useCustomersQuery } from "../../../../features/rtkquery/customersApi";

  const {data, error, isLoading, isSuccess, isFetching} = useCustomersQuery();

  console.log(data)

< Tbody > {
    data
    .map((customers) => {
      return ( <
        CustomersTable key = {
          customers.uid
        }
        name = {
          `${customers.first_name} ${customers.last_name}`
        }
        logo = {
          customers.logo
        }
        id = {
          customers.uid
        }
        exchange = {
          customers.exchange
        }
        createdAt = {
          moment(customers.createdAt).format('LLL')
        }
  /Tbody>
import {
  createApi,
  fetchBaseQuery
} from '@reduxjs/toolkit/query/react'

export const customersApi = createApi({
  reducerPath: "customersApi",
  baseQuery: fetchBaseQuery({
    baseUrl: 'http://localhost:8000',
    credentials: 'same-origin',
    prepareHeaders: (headers, {
      getState
    }) => {
      const token = getState().auth.user.token;
      if (token) {
        headers.set('authorization', `Bearer ${token}`)
      }

      return headers
    },
  }),

  endpoints: (builder) => ({
    customers: builder.query({
      query: () => '/api/v1/customer/paginate-customer',
    })
  })
})

export const {
  useCustomersQuery
} = customersApi
1个回答

此时您的数据可能仍在加载,您必须在数据完成之前渲染一些内容。

在返回组件的真实 jsx 之前,请执行类似

if (isLoading) return <div>loading...</div>
if (isError) return <div>oh no, an error!</div>

的操作。

phry
2023-04-15