【问题标题】:Reusing getStaticProps in Next.js在 Next.js 中重用 getStaticProps
【发布时间】:2022-02-10 15:20:14
【问题描述】:

我正在使用 Next.js 和 GraphCMS 创建博客,并且我有一个出现在多个页面上的 ArticleList 组件(例如,在我的主页上,作为推荐的每篇文章下方等)。

但是,由于文章列表是从我的 CMS 中填充的,因此我使用的是 getStaticProps。因为我不能在组件级别使用 getStaticProps,所以我在每个页面上都重写了相同的 getStaticProps 函数。有什么方法可以让我轻松重用这段代码并跨页面共享?

很想知道这方面是否有任何最佳做法。

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    您可以使用re-export 在单独的文件中定义您的getStaticProps 函数,例如:

    // 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"
    

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2021-12-30
      • 2023-01-04
      • 2021-02-25
      • 2021-03-17
      • 2021-10-17
      • 2020-12-18
      • 2020-10-29
      • 2021-06-22
      相关资源
      最近更新 更多