Next 13 — 客户端和异步服务器组件组合:“Promise<Element>”不是有效的 JSX 元素

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

我正在玩实验性的 Next 13 app 目录。

根据文档,客户端组件可以接受服务器组件,只要它是一个children prop.

有效,但是我确实遇到类型错误

'ServerPage' 不能用作 JSX 组件。它的返回类型 “Promise”不是有效的 JSX 元素。 类型“Promise”缺少类型“ReactElement”中的以下属性:type、props、key

import ClientPage from './clientPage';
import ServerPage from './serverPage';

// app/page.tsx
export default function Home() {
  // logs in the server
  console.log('rendering home page');

  return (
    <>
      <ClientPage>
        <ServerPage /> // type error here
      </ClientPage>
    </>
  );
}

serverPage.tsx 组件

const fetchSomeData = async () => {
  const response = await fetch('https://pokeapi.co/api/v2/pokemon/ditto');

  if (!response.ok) {
    throw new Error(response.statusText);
  }

  return response.json();
};

export default async function ServerPage() {
  const data = await fetchSomeData();
  // this logs in the server
  console.log(data);

  return (
    <>
      <main className={styles.main}>
        Im a server component
      </main>
    </>
  );
}

clientPage.tsx 组件

'use client';

export default function ClientPage({
  children,
}: {
  children: React.ReactNode;
}) {
  // this logs in the client
  console.log('rendering client page');
  return (
    <>
      {children}
    </>
  );
}

我想这与孩子在 clientPage 组件中输入有关,但我不确定应该如何输入。

reactjs typescript next.js
1个回答
0
投票

不幸的是,目前唯一的解决方法是在异步服务器组件上使用 :any 类型定义。 Next.js 13 在他们的 Typescript 文档.

中概述了这一点

警告:您可以在布局和页面中使用异步/等待,它们是服务器组件。在其他组件中使用 async/await 和 TypeScript 可能会导致 JSX 的响应类型出错。您可能会看到错误“Promise”不是有效的 JSX 元素。我们在这里跟踪这个问题.

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