代码之家  ›  专栏  ›  技术社区  ›  Сергей

RTK查询无法取消请求

  •  0
  • Сергей  · 技术社区  · 1 年前

    这样的问题。当没有用户时,我需要跳过请求。 我试着做这个和那个

    const { data: carts = [] as ICart[], isFetching } =
     api.useGetCartProductsQuery(user.id, { skip: !user})
    
    const { data: carts = [] as ICart[], isFetching } =
     api.useGetCartProductsQuery(user.id, { skip: true })
    

    但每次我出错

    Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'id')
    
    Source
    src\app\dashboard\Dashboard.tsx (35:35) @ id
    
      33 | 
      34 |  const { isLoading, data: carts = [] as ICart[] } =
    > 35 |      api.useGetCartProductsQuery(user.id, { skip: true })
    

    告诉我如何使它正确工作。

    我试着做这个和那个

    const { data: carts = [] as ICart[], isFetching } =
     api.useGetCartProductsQuery(user.id, { skip: !user})
    
    const { data: carts = [] as ICart[], isFetching } =
     api.useGetCartProductsQuery(user.id, { skip: true })
    
    0 回复  |  直到 1 年前
        1
  •  0
  •   phry    1 年前

    您在同一时间仍在尝试访问 user.id -这是在RTK Query之外执行的JavaScript代码,您已经编写了:

    api.useGetCartProductsQuery(user.id, { skip: !user })
    

    您可以尝试通过提供某种类型或默认值来绕过这一点:

    api.useGetCartProductsQuery(user ? user.id : undefined, { skip: !user })
    

    但读起来有点不满意。

    相反,您可以使用 skipToken (从RTK查询导出)

    api.useGetCartProductsQuery(user ? user.id : skipToken)