【问题标题】:Generate multiple pages using getServerSideProps with NextJS使用带有 NextJS 的 getServerSideProps 生成多个页面
【发布时间】:2021-11-17 14:51:12
【问题描述】:

我的演示 API 将返回

[
  {
    title: "First article",
    id: "1"
  },
  {
    title: "Second article",
    id: "2"
  }
]

我想为每个人创建一个页面。

组件将被放置在pages/articles/[id].js

我的组件将如下所示

function Article(props) {
  console.log(props)
  return <div>...</div>
}

export async function getServerSideProps(context) {
  const res = await fetch("https://.../articles");
  const data = await res.json()

  if (!data) {
    return {
      notFound: true,
    }
  }

  return {
    props: { data }
  }
}

这将创建一个页面,但将整个提要作为道具。 如何为每个对象创建一个页面?

https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering 这只是告诉我如何为单篇文章创建唯一页面

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    我的解决方案:

    export async function getServerSideProps(context) {
      const articleId = context.query.id;
      const res = await fetch("https://.../articles");
      const articles = await res.json();
    
      const [article] = articles.filter((article) => article.id === articleId);
    
      return {
        props: { article },
      };
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2020-11-13
      • 2022-01-10
      • 2021-07-15
      • 1970-01-01
      • 2021-04-09
      • 2021-05-23
      • 2020-08-04
      • 2022-11-25
      相关资源
      最近更新 更多