我已使用 prisma 将 Planetscale 数据库连接到我的下一个应用程序,并使用 shadcn/ui 数据表成功在表中显示数据。但在该数据表中,有一个分页功能,它将自动根据给定数据的大小对其进行分页。但为了干净地运行它,我需要在获取时直接使用分页来获取。
因此,我使用 zustand 进行状态管理,并尝试应用skip 并接受 prisma 进行索引。这就是我遇到问题的地方。
在我的商店页面
/store
我有一个名为StoreTable
的单独组件
"use client";
import { Products, columns } from "@/app/store/columns";
import { DataTable } from "@/app/store/data-table";
import prismadb from "@/lib/prismadb";
import { useProductPagination } from "@/lib/store/product-pagination";
import React from "react";
async function getData(): Promise<Products[]> {
const { page, perPage } = useProductPagination();
const products = await prismadb.product.findMany({
skip: perPage,
take: page,
});
return products.map((product, i) => ({
id: i + 1,
name: product.name,
description: product.description,
category: product.category,
origin: product.origin,
sell: product.sellingPrice,
purchase: product.purchasedPrice,
amount: Math.random() * 100,
status: product.status == "active" ? "active" : "inactive",
}));
}
async function StoreTable() {
const data = await getData();
return (
<div className="w-screen pr-4 sm:pr-8 md:pr-10 max-w-7xl mx-auto">
<DataTable data={data} columns={columns} />
</div>
);
}
export default StoreTable;
当我运行它时,它会抛出错误
useRef only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component
。 getData 函数需要服务器操作,而 zustand 的挂钩需要客户端渲染。那么有没有更好的方法来处理分页?
在我的数据表中我尝试这样做。
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => {
setPage(page + 10);
setPerPage(perPage + 10);
}}
disabled={!table.getCanNextPage()}>
<span className="sr-only">Go to next page</span>
<FiChevronRight className="h-4 w-4" />
</Button>
我的 zustand 商店是
import {create} from 'zustand'
interface ProductPagination {
page: number
perPage: number
setPage: (page: number) => void
setPerPage: (perPage: number) => void
}
export const useProductPagination = create<ProductPagination>()((set) => ({
page: 10,
perPage: 0,
setPage: (page: number) => set({ page}),
setPerPage: (perPage: number) => set({ perPage})
}))
要解决这个问题,您需要更清楚地分离服务器端和客户端逻辑。以下是有关如何在您的场景中实现分页的建议:
将分页逻辑保留在使用 Zustand 的客户端代码中。 根据Zustand设置的分页参数,在需要的时候从服务器端获取数据。
通常,当您收到该错误时,意味着您正在尝试使用服务器端组件中的客户端挂钩或功能。您必须在代码中的某个位置使用了
useRef
,并且没有在文件顶部使用 use client;
指令