Next.js 中 NextPage 类型的用法

Dan*_*ozi 5 typescript next.js

谁能描述NextPageNext.js TypeScript 项目中的类型?

每个网站都只是说它用于 Next.js 中的类型分配,但我想知道为什么我们应该使用它?它有什么用呢?为什么我们应该使用 this 而不是React.Nodeor React.Fc

jul*_*ves 11

为了更好地理解该NextPage类型,让我们看看它在 Next.js 中的类型定义。

export type NextPage<P = {}, IP = P> = NextComponentType<NextPageContext, IP, P>
Run Code Online (Sandbox Code Playgroud)

它由另一个 type 定义NextComponentType,该 type 又定义如下。

export declare type NextComponentType<C extends BaseContext = NextPageContext, IP = {}, P = {}> = ComponentType<P> & {
    /**
     * Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered.
     * Make sure to return plain `Object` without using `Date`, `Map`, `Set`.
     * @param ctx Context of `page`
     */
    getInitialProps?(context: C): IP | Promise<IP>;
};
Run Code Online (Sandbox Code Playgroud)

该类型直接扩展了 React ComponentType,并getInitialProps作为可选属性添加。

从本质上讲,NextPage类型允许正确键入页面组件,其中包括getInitialProps(尽管自引入以来并不常见getServerSideProps)。

最后,虽然您可以在不包含的页面组件上使用 React 的内置类型而不会出现getInitialProps问题,但建议使用 Next.js 提供的类型。它将使您的代码更加面向未来和惯用,以防在框架级别添加/删除任何内容。

  • @danikaze 我不建议将 `NextPage` 类型与 Next.js 13 `app` 文件夹一起使用。 (2认同)