【问题标题】:Next.js ISR pass additional data to getStaticProps from getStaticPathsNext.js ISR 将附加数据从 getStaticPaths 传递给 getStaticProps
【发布时间】:2022-05-05 00:39:56
【问题描述】:

SingleBlogPost.jsx 我有:

export async function getStaticPaths() {
  const res = await fetch("http://localhost:1337/api/posts");
  let { data } = await res.json();

  const paths = data.map((data) => ({
    params: { slug: data.attributes.slug },
  }));

  return {
    paths,
    fallback: "blocking",
  };
}

我通过他们的 slug 生成博客页面。 但是在 getStaticProps 中,我需要通过 slug 获取单个帖子,但我想通过 id 来获取。

export async function getStaticProps(context) {
  console.log("context", context);

  const { slug } = context.params;

  console.log("slug is:", slug);
  const res = await fetch("http://localhost:1337/api/posts");
  const { data } = await res.json();

  return {
    props: {
      data,
    },

    revalidate: 10, // In seconds
  };
}

我想保留像 /blog/:slug 这样的 url,我不想包含 id。在 url 中。当我已经获取 getStaticPaths 中的所有帖子时,如何访问 getStaticProps 中的帖子 ID 以避免通过 slug 获取?

【问题讨论】:

  • 看看这个帖子,一些有用的答案贴在here

标签: javascript reactjs next.js


【解决方案1】:

我找到了一个使用 object-hash 包的简洁解决方法。我基本上创建了 params 对象的哈希,并使用它在 set 和 get 上创建 tmp 文件名。 tmp 文件包含一个 json,其中包含我想在两个臭名昭著的静态回调之间传递的数据。

要点:

function setParamsData({params, data}) {
  const hash = objectHash(params)
  const tmpFile = `/tmp/${hash}.json`

  fs.writeFileSync(tmpFile, JSON.stringify(data))
}

function getParamsData (context) {
  const hash = objectHash(context.params)
  const tmpFile = `/tmp/${hash}.json`

  context.data = JSON.parse(fs.readFileSync(tmpFile))

  return context
}

然后我们可以在getStaticPathsgetStaticProps 回调中使用这些帮助器在它们之间传递数据。

export function getStaticPaths(context) {
  setParamsData({...context, data: {some: 'extra data'})

  return {
    paths: [],
    fallback: false,
  }
}

export function getStaticProps(context) {
  context = getParamsData(context)

  context.data // => {some: 'extra data'}
}

我相信有人会想出更好的 API,然后重新分配参数变量。

tmp 文件的创建可能不够独立于操作系统,可能需要一些改进。

【讨论】:

    【解决方案2】:

    看起来最近发布了一个使用文件系统缓存的解决方法。

    解决方案的关键是他们将 body 对象保存在内存中,使用如下方式:

    this.cache = Object.create(null)

    并创建方法来更新和从缓存中获取数据。

    在这里讨论:https://github.com/vercel/next.js/discussions/11272#discussioncomment-2257876

    示例代码: https://github.com/vercel/examples/blob/main/build-output-api/serverless-functions/.vercel/output/functions/index.func/node_modules/y18n/index.js#L139:10

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2020-12-18
      • 2019-04-11
      • 2020-12-20
      • 2021-03-14
      • 2013-03-01
      • 1970-01-01
      相关资源
      最近更新 更多