【问题标题】:how to generate dynamic pages without knowing the static paths on NextJS?如何在不知道 NextJS 上的静态路径的情况下生成动态页面?
【发布时间】:2021-06-02 11:01:19
【问题描述】:

我想将我的用户引导到一个页面,在该页面上,他们可以根据公民身份号码获得折扣。我将使用他们的身份证号码来确定他们获得的折扣金额。我可以使用他们的 id 来确定位置、年龄、性别等。

他们可以路由到 mywebsite.com/megadiscount 并在一个框中填写他们的 ID 号,然后了解他们可以获得多少折扣。但现在的问题是,我还希望他们能够获得指向 mywebsite.com/megadiscount/[id number] 的链接,以了解他们可以获得多少折扣。

所以使用 NextJS,我知道我可以创建 megadiscount/index.jsmegadiscount/[id].js 来从 url 中捕获 id。

问题是在megadiscount/[id].js 上我必须用getStaticPaths 指定我将生成的ID 页面,但问题是我不知道这些ID 将是什么。

我的megadiscount/[id].js 文件如下所示

const Page = ({discount}) => {
  return (
    <>
      <h1>You get a discount of : {discount}%</h1>
    </>
  )
}


export async function getStaticPaths() {

  return {
    paths: [], // I don't know what these will be
    fallback: false,
  };
}

export async function getStaticProps(context) {
  const { slug = "" } = context.params;
  const discount = fetchDiscountFromServer(slug)
  return {
    props: {
      discount
    },
  };
}

export default Page;

【问题讨论】:

  • 你可以使用``` fallback: "blocking", ``` 在这种情况下

标签: javascript next.js dynamic-routing


【解决方案1】:
export default function Page({ discount }) {
  return (
    <>
      <h1>You get a discount of : {discount}%</h1>
    </>
  );
}

export async function getStaticProps({ params: { id } }) {
  //Featch your discount based on id
  const discount = await fetchDiscountFromServer(id);
  return {
    props: { discount },
  };
}
export async function getStaticPaths() {
  return {
    paths: [],
    fallback: "blocking",
  };
}

NextJS 为这种情况提供了回退:“阻塞”。查看docs

但是在我看来,在这种情况下你应该考虑SSR。这将为每个用户生成一个静态页面,这很好,但如果您经常更改折扣,您必须设置一个较低的 revalidate:1 value,但这仍然不是实时的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2020-02-16
    • 2015-02-17
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多