【问题标题】:Usage of NextPage type in Next.jsNext.js 中 NextPage 类型的使用
【发布时间】:2022-01-09 06:17:29
【问题描述】:

谁能在 Next.js TypeScript 项目中描述 NextPage 类型?

每个站点都只是说它是用于 Next.js 中的类型分配,但我想知道为什么我们应该使用它?它的用途是什么?为什么要使用这个而不是React.NodeReact.Fc

【问题讨论】:

    标签: typescript next.js


    【解决方案1】:

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

    export type NextPage<P = {}, IP = P> = NextComponentType<NextPageContext, IP, P>
    

    它由另一个类型NextComponentType定义,其定义如下。

    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>;
    };
    

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

    基本上,NextPage 类型允许正确键入包含 getInitialProps 的页面组件(尽管自引入 getServerSideProps 以来并不常见)。

    最后,虽然您可以在不包含 getInitialProps 的页面组件上毫无问题地使用 React 的内置类型,但建议使用 Next.js 提供的类型。如果在框架级别添加/删除任何内容,它将使您的代码更具前瞻性和惯用性。

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 2019-11-23
      • 1970-01-01
      • 2022-08-15
      相关资源
      最近更新 更多