reactjs 如何在Next JS中使用客户端组件中的javascript/await?

krcsximq  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(172)

我已经在这方面工作了一段时间,我甚至不能使它工作.问题是,我想通过一个值到我的服务器动作prisma从我的状态管理上下文.但每次我试图运行我的代码,它抛出一个错误.
在我的客户端组件中

"use client";
import { Products, columns } from "@/app/store/columns";
import { DataTable } from "@/app/store/data-table";
import { getData } from "@/lib/store/get-product";
import { useProductPagination } from "@/lib/store/product-pagination";
import React from "react";

async function StoreTable() {
  const { page, perPage } = useProductPagination();

  const data = await getData(perPage, page);
  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;

字符串
我尝试处理的服务器操作是

import { Products } from "@/app/store/columns";
import prismadb from "../prismadb";

export async function getData(perPage: number, page: number): Promise<Products[]> {
    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",
    }));
  }


但我面临的错误是Error: async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding '使用客户端' to a module that was originally written for the server.
我试图做的是实现分页到我的数据表和处理在prisma页.但我没有idea什么我必须做.
所以请帮帮我

dsekswqp

dsekswqp1#

使用client components你不能直接调用一个等待的函数(API请求)。所以你应该使用useEffect来使事情正常工作。你能试试下面的代码吗:

import { useState, useEffect } from 'react';
import { Products, columns } from "@/app/store/columns";
import { DataTable } from "@/app/store/data-table";
import { getData } from "@/lib/store/get-product";
import { useProductPagination } from "@/lib/store/product-pagination";
import React from "react";

function StoreTable() {
  const { page, perPage } = useProductPagination();
  const [data, setData] = useState([]); // based on your data you should store it here in state

  useEffect(() => {
    const fetchData = async () => {
      try {
        const result = await getData(perPage, page);
        setData(result);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [perPage, page]);

  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;

字符串
希望这对你有帮助!祝你好运:)。

相关问题