如何使Next.js getStaticProps使用TypeScrip

p1tboqfb  于 2022-10-01  发布在  其他
关注(0)|答案(6)|浏览(276)

我正在使用启用了打印功能的Next.js

尝试使用此处所述的getStaticProps https://nextjs.org/docs/basic-features/typescript

使用GetStaticProps类型

export const getStaticProps: GetStaticProps = () => {
    return {
        props: {
            host: process.env.DB_HOST.toString(),
        },
    }
}

我收到像这样的错误

Type '() => { props: { host: string; }; }' is not assignable to type 'GetStaticProps<{ [key: string]: any; }, ParsedUrlQuery>'.
  Type '{ props: { host: string; }; }' is missing the following properties from type 'Promise<GetStaticPropsResult<{ [key: string]: any; }>>': then, catch, [Symbol.toStringTag], finallyts(2322)

我刚开始打字,所以我很难弄清楚它想要什么,

如有任何帮助,我将不胜感激,提前谢谢

以下是整个页面代码

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import React from 'react'
import { GetStaticProps, GetStaticPropsContext } from 'next'

interface Props {
    host: string
}

const Home: React.FC<Props> = (props) => {
    return (
        <div className={styles.container}>
            <Head>
                <title>Create Next App</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>

            <main className={styles.main}>
                aa:{props.host}
                <h1 className={styles.title}>
                    Welcome to <a href="https://nextjs.org">Next.js!</a>
                </h1>
                <p className={styles.description}>
                    Get started by editing <code className={styles.code}>pages/index.js</code>
                </p>
                <div className={styles.grid}>
                    <a href="https://nextjs.org/docs" className={styles.card}>
                        <h3>Documentation &rarr;</h3>
                        <p>Find in-depth information about Next.js features and API.</p>
                    </a>

                    <a href="https://nextjs.org/learn" className={styles.card}>
                        <h3>Learn &rarr;</h3>
                        <p>Learn about Next.js in an interactive course with quizzes!</p>
                    </a>

                    <a
                        href="https://github.com/vercel/next.js/tree/master/examples"
                        className={styles.card}
                    >
                        <h3>Examples &rarr;</h3>
                        <p>Discover and deploy boilerplate example Next.js projects.</p>
                    </a>

                    <a
                        href="https://vercel.com/import?filter=next.js&utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
                        className={styles.card}
                    >
                        <h3>Deploy &rarr;</h3>
                        <p>Instantly deploy your Next.js site to a public URL with Vercel.</p>
                    </a>
                </div>
            </main>

            <footer className={styles.footer}>
                <a
                    href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
                    target="_blank"
                    rel="noopener noreferrer"
                >
                    Powered by <img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
                </a>
            </footer>
        </div>
    )
}

export const getStaticProps: GetStaticProps = () => {
    return {
        props: {
            host: process.env.DB_HOST.toString(),
        },
    }
}

export default Home
kx1ctssn

kx1ctssn1#

嗨,遇到了你的问题,但上面的答案都没有帮到我。

我快速阅读了一下文档:https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation

并发现您的getStaticProps的正确类型应该是:

import { GetStaticProps } from 'next'

export const getStaticProps: GetStaticProps = async (context) => {
  // ...
}

然后在您的组件中:

import { InferGetStaticPropsType } from 'next'

type Post = {
  author: string
  content: string
}

export const getStaticProps = async () => {
  const res = await fetch('https://.../posts')
  const posts: Post[] = await res.json()

  return {
    props: {
      posts,
    },
  }
}

function Blog({ posts }: InferGetStaticPropsType<typeof getStaticProps>) {
  // will resolve posts to type Post[]
}

export default Blog

这会将类型从GetStaticProps自动生成到您的组件它对我100%有效

qv7cva1a

qv7cva1a2#

您的原始示例几乎是正确的,但是getStaticProps函数表达式缺少async。试试这个:

export const getStaticProps: GetStaticProps = async () => { // must be async
  return {
    props: {
      host: process.env.DB_HOST.toString(),
    },
  };
};

这不是因为TS,而是因为在Next.js中对getStaticProps()的实际定义。

回到您的示例中,更好的做法是使用通用道具改进输入:

interface Props {
  host: string;
}

export const getStaticProps: GetStaticProps<Props> = async () => {
  return {
    props: {
      host: process.env.DB_HOST.toString(),
    },
  };
};
ulmd4ohb

ulmd4ohb3#

答案如下:

export async function getStaticProps(context): Promise<GetStaticPropsResult<HomeProps>> {
    return {
        props: {
            host: process.env.DB_HOST,
        },
    };
}

我的同事通过检查GetStaticProps类型定义找到了解决方案:

以下是整个页面代码

import Head from "next/head";
import styles from "../styles/Home.module.css";
import React from "react";
import { GetStaticPropsResult, GetStaticProps } from "next";

interface HomeProps {
    host: string;
}

const Home: React.FC<HomeProps> = (props: HomeProps) => {
    return (
        <div className={styles.container}>
            <Head>
                <title>Create Next App</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>

            <main className={styles.main}>
                aa:{props.host}
                <h1 className={styles.title}>
                    Welcome to <a href="https://nextjs.org">Next.js!</a>
                </h1>
                <p className={styles.description}>
                    Get started by editing <code className={styles.code}>pages/index.js</code>
                </p>
                <div className={styles.grid}>
                    <a href="https://nextjs.org/docs" className={styles.card}>
                        <h3>Documentation &rarr;</h3>
                        <p>Find in-depth information about Next.js features and API.</p>
                    </a>

                    <a href="https://nextjs.org/learn" className={styles.card}>
                        <h3>Learn &rarr;</h3>
                        <p>Learn about Next.js in an interactive course with quizzes!</p>
                    </a>

                    <a href="https://github.com/vercel/next.js/tree/master/examples" className={styles.card}>
                        <h3>Examples &rarr;</h3>
                        <p>Discover and deploy boilerplate example Next.js projects.</p>
                    </a>

                    <a
                        href="https://vercel.com/import?filter=next.js&utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
                        className={styles.card}
                    >
                        <h3>Deploy &rarr;</h3>
                        <p>Instantly deploy your Next.js site to a public URL with Vercel.</p>
                    </a>
                </div>
            </main>

            <footer className={styles.footer}>
                <a
                    href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
                    target="_blank"
                    rel="noopener noreferrer"
                >
                    Powered by <img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
                </a>
            </footer>
        </div>
    );
};

export async function getStaticProps(context): Promise<GetStaticPropsResult<HomeProps>> {
    return {
        props: {
            host: process.env.DB_HOST,
        },
    };
}

export default Home;
agxfikkp

agxfikkp4#

简而言之,将其用于不断重复使用:

export const getStaticProps = async ({
    params,
}: GetStaticPropsContext<PageParams>): Promise<
    GetStaticPropsResult<ContentPageProps>
> => {
    const { title, description } = await fetch(".../entity", { uuid: params.uuid })
    return {
        props: {
            title,
            description,
        },
    }
}

下面是我在page/content.tsx中正确键入getStaticProps的样子:

import type {
    GetStaticPathsResult,
    GetStaticPropsContext,
    GetStaticPropsResult,
} from 'next'

type PageParams = {
   uuid: string
}

type ContentPageProps = {
   title: string
   description: string
}

export default const ContentPage = ({ title, description }: ContentPageProps): JSX.Element => {
    return (
        <>
             <h1>{title}</h1>
             <p>{description}</p>
        </>
    )
}

export const getStaticProps = async ({
    params,
}: GetStaticPropsContext<PageParams>): Promise<
    GetStaticPropsResult<ContentPageProps>
> => {
    const { title, description } = await fetch(".../entity", { uuid: params.uuid })
    return {
        props: {
            title,
            description,
        },
    }
}

export const getStaticPaths = async ({}): Promise<
    GetStaticPathsResult<PageParams>
> => {
    return {
        paths: { params: { uuid: "54b659a1-3f20-4440-90b5-9107bd62b5ca" }},
        fallback: false,
    }
}

告示

async (context:GetStaticPropsContext<PageParams>):
    Promise<GetStaticPropsResult<ContentPageProps>

其中PageParams派生自ParsedUrlQueryContentPageProps是您将放入组件中以呈现的内容,可以通过任何复杂性(但不是递归)进行呈现。

nkoocmlb

nkoocmlb5#

我和奥普拉遇到了同样的麻烦。这个教程非常适合我:https://www.vitamindev.com/next-js/getstaticprops-getstaticpaths-typescript/。它解决了getStaticPaths需要ParsedUrlQuery类型的问题。作者提供了扩展,作为一种解决方案。请准确命名您的物业(!)否则TS会抱怨的。

zzlelutf

zzlelutf6#

在2022年这样做的正确方法是利用Next.js类型中的泛型。

import type { NextPage, GetStaticProps } from "next";
// ...

interface HomeProps {
  host: string
}

const Home: NextPage<HomeProps> = (props) => {
  // ...
};

export const getStaticProps: GetStaticProps<HomeProps> = async () => {
  // ...
};

相关问题