只有普通对象和一些内置对象可以从服务器组件传递到客户端组件。不支持类或空原型

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

当我通过 queryclientprovider 包装 App.ts 时,出现此错误只有普通对象和一些内置对象可以从服务器组件传递到客户端组件。不支持类或空原型。所以App.ts的代码是





 import Image from 'next/image'
import { Button } from '@/components/ui/button'
import { UserButton,auth } from '@clerk/nextjs'
import Link from 'next/link';
import {LogIn } from 'lucide-react';
import FileUpload from '@/components/FileUpload';
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";



export default async function Home() {

  const queryClient = new QueryClient();
  const {userId}=await auth();
  const isAuth=!!userId
  return (
    <QueryClientProvider client={queryClient}>
    <div className='w-screen min-h-screen bg-gradient-to-b from-black via-black to-sky-900'>
      <div className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white'>
         <div className="flex flex-col items-center text-center">
          <div className="flex items-center"> 
          <h1 className='mr-3 text-5xl font-bold-sans md:font-serif  bg-clip-text text-transparent bg-gradient-to-r from-white to-gray-400 '>Chat With Any PDF</h1>
          <UserButton afterSignOutUrl='/'/>
          </div>
          <div className="flex mt-2">
            {isAuth &&
          <Button className=' mb-2 bg-gradient-to-r  from-black via-black to-sky-900 border-2 border-gray-300 border-r-2  hover:bg-gradient-to-l  hover:transition hover:duration-300   '>Go to Chats</Button>}
          </div>
          <p className='  mt-1   md:font-serif  bg-clip-text text-transparent bg-gradient-to-r from-white to-gray-400 '>Script.Ai is a cutting-edge web application designed to streamline your PDF interactions. Simply upload your documents and effortlessly extract answers to your questions, harnessing the power of advanced AI technology for precision and efficiency.</p>
          <div className='w-full mt-4'>
          
   
            {isAuth ? (<FileUpload/>):<Link href={'/sign-in'} >
          

            <Button  className=' bg-gradient-to-r from-black via-black to-sky-900  text-gray-300 border-2 border-gray-300  hover:bg-gradient-to-l  hover:transition hover:duration-300 hover:ease-in-out'>Login to get Started
            <LogIn className='w-4 h-4 ml-2 '/></Button>
            </Link> }
          </div>
          
         </div>
      </div>
    </div>
  </QueryClientProvider>
  )
}




我使用“useMutation”的queryclient bcse的文件FileUpload.ts的代码是

"use client";
import { uploadToS3 } from "@/lib/s3";
import { useMutation } from "@tanstack/react-query";
import { Inbox, Loader2 } from "lucide-react";
import React from "react";
import { useDropzone } from "react-dropzone";
import axios from "axios";
import { toast } from "react-hot-toast";
import { useRouter } from "next/navigation";

// https://github.com/aws/aws-sdk-js-v3/issues/4126

const FileUpload = () => {
  const router = useRouter();
  const [uploading, setUploading] = React.useState(false);
  const { mutate, isPending } = useMutation({
    mutationFn: async ({
      file_key,
      file_name,
    }: {
      file_key: string;
      file_name: string;
    }) => {
      const response = await axios.post("/api/create-chat", {
        file_key,
        file_name,
      });
      return response.data;
    },
  });

  const { getRootProps, getInputProps } = useDropzone({
    accept: { "application/pdf": [".pdf"] },
    maxFiles: 1,
    onDrop: async (acceptedFiles) => {
      const file = acceptedFiles[0];
      if (file.size > 10 * 1024 * 1024) {
        // bigger than 10mb!
        toast.error("File too large");
        return;
      }

      try {
        setUploading(true);
        const data = await uploadToS3(file);
        console.log("meow", data);
        if (!data?.file_key || !data.file_name) {
          toast.error("Something went wrong");
          return;
        }
        mutate(data, {
          onSuccess: ({ chat_id }) => {
            toast.success("Chat created!");
            router.push(`/chat/${chat_id}`);
          },
          onError: (err) => {
            toast.error("Error creating chat");
            console.error(err);
          },
        });
      } catch (error) {
        console.log(error);
      } finally {
        setUploading(false);
      }
    },
  });
  return (
    <div className="p-2 bg-white rounded-xl">
      <div
        {...getRootProps({
          className:
            "border-dashed border-2 rounded-xl cursor-pointer bg-gray-50 py-8 flex justify-center items-center flex-col",
        })}
      >
        <input {...getInputProps()} />
        {uploading || isPending ? (
          <>
            {/* loading state */}
            <Loader2 className="h-10 w-10 text-blue-500 animate-spin" />
            <p className="mt-2 text-sm text-slate-400">
              Spilling Tea to GPT...
            </p>
          </>
        ) : (
          <>
            <Inbox className="w-10 h-10 text-blue-500" />
            <p className="mt-2 text-sm text-slate-400">Drop PDF Here</p>
          </>
        )}
      </div>
    </div>
  );
};

export default FileUpload;

请帮我解决这个错误

javascript typescript amazon-s3 next.js runtime-error
1个回答
0
投票

看来您正在使用next js 14。将nextjs14与react-query一起使用。您必须将 QueryClientProvider 包含在客户端组件中:

"use client"

import { useState } from 'react';
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";


const Provider = ({ children }) => {
    const [client] = useState(new QueryClient())

    return <QueryClientProvider client={client}>{children}</QueryClientProvider>
} 


In-App.ts 文件:


export default async function Home() {
  return (
     <Provider>
        ....
     </Provider>
  )
}

原因:

Next JS 14 不允许在服务器渲染组件中直接使用提供程序和上下文,因为服务器渲染组件只是作为响应传输的 HTML。借助客户端组件,您可以轻松创建客户端提供程序。

更多参考:查看这篇文章

© www.soinside.com 2019 - 2024. All rights reserved.