简体   繁体   English

在 Next.js 中重用 getStaticProps

[英]Reusing getStaticProps in Next.js

I'm creating a blog with Next.js and GraphCMS, and I have an ArticleList component that appears on multiple pages (eg on my homepage, under each article as a recommendation, etc.).我正在使用 Next.js 和 GraphCMS 创建一个博客,并且我有一个出现在多个页面上的 ArticleList 组件(例如,在我的主页上,在每篇文章下面作为推荐等)。

However, since the article list is being populated from my CMS, I'm using getStaticProps.但是,由于文章列表是从我的 CMS 填充的,所以我使用的是 getStaticProps。 And since I can't use getStaticProps on the component-level, I'm re-writing the same getStaticProps function on every single page.由于我无法在组件级别使用 getStaticProps,因此我在每个页面上都重写了相同的 getStaticProps function。 Is there any way for me to easily reuse this code and share it across pages?有什么方法可以让我轻松地重用这段代码并跨页面共享吗?

Would love to know if there are any best practices for this.很想知道是否有任何最佳实践。

在此处输入图像描述

You could define your getStaticProps function in a separate file, using a re-export , for example:您可以使用re-export在单独的文件中定义getStaticProps function ,例如:

// lib/getStaticProps.js

export function getStaticProps(context) {
  return {
    props: {
      // some cool props
    },
  }
}
// pages/index.js

export default function Page(props) {
  // ...
}

export { getStaticProps } from "../lib/getStaticProps"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM