You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js Server组件向Client组件传Props时构建报错求助

问题

开发运行时从Server组件向Client组件传递Props无报错,但构建阶段出现类型错误,提示src/app/chat/Agents/page.tsx的默认导出类型{ data: any; }无效。

原因及解决方法

核心原因

Next.js构建阶段会对Server→Client传递的Props进行严格的类型检查和序列化验证,使用any类型会绕过类型系统触发构建错误;同时冗余的JSON.parse(JSON.stringify())操作无意义,还可能引发潜在类型问题。

解决步骤

  1. 替换any为明确类型定义:为Client组件的Props创建接口,明确数据结构,让TypeScript能正确校验传递参数。
  2. 优化Server组件数据传递:直接传递对象即可,Next.js会自动处理可序列化数据的传递,无需额外JSON序列化操作。
  3. 完善异步函数类型安全:为异步函数指定返回类型,确保返回值类型明确,避免null带来的潜在类型隐患。

修改后的代码

Client组件(src/app/chat/Agents/page.tsx)

"use client";

import { useState } from "react";
import frontEndAxiosInstance from "@/app/lib/frontendaxiosInstance";

// 定义Props的明确类型
interface AgentsPageProps {
  data: {
    knowledgeId: string;
    documentId: string;
  };
}

const AgentsPage = ({ data }: AgentsPageProps) => {
  const [first, setfirst] = useState("test");
  return (
    <div id="status">
      <h4>hello</h4>
      <p>Knowledge ID: {data.knowledgeId}</p>
      <p>Document ID: {data.documentId}</p>
    </div>
  );
};

export default AgentsPage;

Server组件

import React, { Suspense } from "react";
import frontEndAxiosInstance from "@/lib/frontendaxiosInstance";
import AgentsPage from "./Agents/page";

// 为异步函数指定返回类型
async function CreateKnowledge(): Promise<string | null> {
  try {
    const response = await frontEndAxiosInstance.post("/knowledge");
    const knowledge = response.data.message;
    if (knowledge && typeof knowledge.id === "string") {
      return knowledge.id;
    }
    return null;
  } catch (error) {
    console.error(error);
    return null;
  }
}

async function CreateDocument(knowledgeId: string): Promise<string | null> {
  try {
    const response = await frontEndAxiosInstance.post(
      `knowledge/${knowledgeId}/documents`
    );
    const document = response.data.data;
    if (document && typeof document.id === "string") {
      return document.id;
    }
    return null;
  } catch (error) {
    console.error(error);
    return null;
  }
}

const Page = async () => {
  const knowledgeId = await CreateKnowledge();
  let documentId: string | null = null;

  if (knowledgeId) {
    documentId = await CreateDocument(knowledgeId);
  }

  if (!knowledgeId || !documentId) {
    return <p>Error creating knowledge or document.</p>;
  }

  // 直接传递结构化数据
  const data = { knowledgeId, documentId };

  return (
    <div>
      <p>KnowledgeId: {knowledgeId}</p>
      <p>DocumentId: {documentId}</p>
      <Suspense fallback={<p>Loading agent...</p>}>
        <AgentsPage data={data} />
      </Suspense>
    </div>
  );
};

export default Page;

内容的提问来源于stack exchange,提问作者desh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 21:35:01