Zustand Hook在细胞表Tanstack

问题描述 投票:0回答:1

我试图将我用zustand创建的钩子呼叫到tanstack表的一个单元格之一,在构建过程中,Eslint抛出了错误

Error: React Hook "useCartStore" is called in function "cell" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".  react-hooks/rules-of-hooks

cell: ({ row }) => {
  const product = row.original
  const productId = product.id
  // Get cart from store to find the current quantity
  const cart = useCartStore((state) => state.cart)
  const updateQuantity = useCartStore((state) => state.updateQuantity)
  const removeItem = useCartStore((state) => state.removeFromCart)

  // Find items in the cart
  const cartItem = cart.find((item) => item.id === productId)
  // Use cart quantity if available, otherwise use the product's default quantity
  const quantity = cartItem ? cartItem.quantity : product.quantity

从中解决的最佳方法是什么?由于细胞不是反应组件

reactjs next.js zustand tanstack tanstack-table
1个回答
0
投票
您会遇到该错误,因为您在单元格方法内呼叫

useCartStore

,这不是反应功能组件。您可以解决此问题的方法是创建功能组件并将逻辑中的逻辑抽象到该组件中,然后将其渲染在表单元格中。以下是您可以实现这一目标的方式:

export const ProductCell = ({ product }: { product: TProduct }) => { const productId = product.id // Get cart from store to find the current quantity const cart = useCartStore((state) => state.cart) const updateQuantity = useCartStore((state) => state.updateQuantity) const removeItem = useCartStore((state) => state.removeFromCart) // Find items in the cart const cartItem = cart.find((item) => item.id === productId) // Use cart quantity if available, otherwise use the product's default quantity const quantity = cartItem ? cartItem.quantity : product.quantity return ( //The Table Cell JSX ); };
在您的表列中,您将其调用类似:

{ cell: ({ row }) => <ProductCell product={row.original} /> },
    
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.