【问题标题】:How to type the getStaticProps function when using getStaticPaths params?使用 getStaticPaths 参数时如何键入 getStaticProps 函数?
【发布时间】:2021-07-10 15:17:53
【问题描述】:

我正在编写以下代码:

这是一个blogPost动态页面:/post/[slug].tsx

export const getStaticPaths: GetStaticPaths = async () => {
  const allSlugs = await getAllSlugs();;
  return ({
    paths: allSlugs.map((slug) => ({ params: { slug }})),
    fallback: "blocking"
  });
};

export const getStaticProps: GetStaticProps = async (context) => {
  const slug = context.params.slug;
  const blogPost = getBlogPostFromSlug({slug});
  return ({
    props: {
      blogPost
    }
  });
};

这是我得到的错误:

看来GetStaticProps 类型是通用的,可以为我的类型自定义。

我创建了这两种类型来尝试自定义GetStaticProps 类型:

type ContextParams = {
  slug: string
}

type PageProps = {
  blogPost: null | Types.BlogPost.Item
}

这是我正在尝试的:

export const getStaticProps: GetStaticProps<PageProps,ContextParams> = async (context) => {
  const slug = context.params.slug;
  const blogPost = await getBlogPostFromSlug({slug});
  return ({
    props: {
      blogPost
    }
  });
};

但它仍然认为params 可能未定义。我应该处理它吗?从上面的代码来看,params 似乎是未定义的?我没想到会这样。

【问题讨论】:

    标签: javascript reactjs typescript next.js static-site-generation


    【解决方案1】:

    类型被定义为使得params 变量仍然必须是undefined,即使您声明了参数Q 的类型。来自the types file

    export type GetStaticPropsContext<Q extends ParsedUrlQuery = ParsedUrlQuery> = {
      params?: Q
    ...
    

    所以如果你想安全,那么你应该假设你可能没有params。我会使用notFoundredirect 属性explained here 来处理缺少params 的请求。您还希望处理您的 async 函数 getBlogPostFromSlug 被拒绝的情况。

    export const getStaticProps: GetStaticProps<PageProps, ContextParams> = async (
      context
    ) => {
      const slug = context.params?.slug;
      if (slug) {
        try {
          const blogPost = await getBlogPostFromSlug({ slug });
          return {
            props: {
              blogPost
            }
          };
        } catch (error) { }
      }
      return {
        notFound: true
      };
    };
    

    Typescript Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 2021-05-22
      • 2022-11-02
      • 2021-04-27
      • 2022-12-05
      • 1970-01-01
      • 2021-03-26
      相关资源
      最近更新 更多