我正在玩实验性的 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
组件中输入有关,但我不确定应该如何输入。
不幸的是,目前唯一的解决方法是在异步服务器组件上使用 :any
类型定义。 Next.js 13
在他们的 Typescript 文档.
警告:您可以在布局和页面中使用异步/等待,它们是服务器组件。在其他组件中使用 async/await 和 TypeScript 可能会导致 JSX 的响应类型出错。您可能会看到错误“Promise”不是有效的 JSX 元素。我们在这里跟踪这个问题.