Fer*_*ted 7 typescript reactjs server-side-rendering next.js next.js13
我正在玩实验性的 Next 13app
目录。
根据文档,客户端组件可以接受服务器组件,只要它作为道具即可children
。
它有效,但是我确实收到类型错误
“ServerPage”不能用作 JSX 组件。它的返回类型“Promise”不是有效的 JSX 元素。类型“Promise”缺少类型“ReactElement<any,any>”中的以下属性:类型、道具、键
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>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
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>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
clientPage.tsx组件
'use client';
export default function ClientPage({
children,
}: {
children: React.ReactNode;
}) {
// this logs in the client
console.log('rendering client page');
return (
<>
{children}
</>
);
}
Run Code Online (Sandbox Code Playgroud)
我认为这与组件中的子级类型有关clientPage
,但我不确定应该如何输入。
要将异步服务器组件与 TypeScript 一起使用,请确保您使用的是 TypeScript 5.1.3 或更高版本以及 @types/react 18.2.8 或更高版本。
如果您使用旧版本的 TypeScript,您可能会看到“Promise”不是有效的 JSX 元素类型错误。更新到最新版本的 TypeScript 和 @types/react 应该可以解决这个问题。
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: { serverActions: true },
};
module.exports = nextConfig;
``
Run Code Online (Sandbox Code Playgroud)
小智 1
不幸的是,目前解决这个问题的唯一方法是:any
在异步服务器组件上使用类型定义。Next.js 13
在他们的Typescript 文档中概述了这一点。
警告:您可以在布局和页面中使用 async/await,它们是服务器组件。使用 TypeScript 在其他组件中使用 async/await 可能会导致 JSX 的响应类型出现错误。您可能会看到错误“Promise”不是有效的 JSX 元素。我们正在此处跟踪此问题。
归档时间: |
|
查看次数: |
7510 次 |
最近记录: |