简体   繁体   中英

Next.js: How to get URL path inside getStaticPaths?

I want get last number by current url pathnames inside getStaticPaths.

http://localhost:3000/category/food/2 -> 2,
http://localhost:3000/category/food/3 -> 3,
...

I tried.

 export const getStaticPaths: GetStaticPaths = async () => {
  // getAllCategories() is fetch(GET) allcategories
  const allCategories = await getAllCategories() //  fetch;

  const num = 2; <- Get number by current url pathnames

  return {
    paths:
      allCategories.edges.map(
        ({ node }: { node: { [key: string]: string } }) =>
          `/category/${node.slug}/${num}`
      ) || [],
    fallback: false,
  };
};

Dose anyone know how to resolve?

In my opinion you are on the wrong way with just getStaticPaths because it is pre-rendered at build time and you do not have access to the path.

You should combine it with getStaticProps where you get a context object to use; for details please read the official documenation -> https://nextjs.org/docs/api-reference/data-fetching/get-static-props and https://nextjs.org/docs/api-reference/data-fetching/get-static-paths

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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