xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Next.js dynamic router path bug All In One

Next.js dynamic router path bug All In One

markdown

daynamic router

bug

why below code not work at all ?

dynamic router path screenshot

image

// [title].js

export async function getStaticPaths() {
  const ids = await getPostsIds();
//   ids[0] =
//     {
//       id: '/Users/xgqfrms-mm/Documents/github/nextjs-ssr/posts/markdown.md',
//       year: '2022',
//       month: '12',
//       day: '31',
//       title: 'last'
//    }
  const paths = ids.map(({id, year, month, day, title}) => ({
    params: {
      // id can not pass `id` with params ❌
      id,
      year,
      month,
      day,
      title,
    },
    // can not pass `id` by using key out of `params` ❌❌
    id,
  }));
  return {
    paths,
    fallback: false,
  };
}


export async function getStaticProps({ params, id }) {
  console.log(`params without id =`, params);
  // params without id = {
  //   params: { year: '2022', month: '12', day: '31', title: 'last' },
  //   locales: undefined,
  //   locale: undefined,
  //   defaultLocale: undefined
  // }
  // both not work ❌
  // const data = await getPostsData(params.id);
  const data = await getPostsData(id);
  return {
    props: {
      postData: data,
    },
  };
}

hack way find id ✅


// [title].js

export async function getStaticPaths() {
  const ids = await getPostsIds();
  const paths = ids.map(({id, year, month, day, title}) => ({
    params: {
      year,
      month,
      day,
      title,
    },
  }));
  return {
    paths,
    fallback: false,
  };
}


export async function getStaticProps({ params }) {
  // hack way find id ✅ 
  const ids = await getPostsIds();
  const obj = ids.find(obj => {
    if(obj.year === params.year && obj.month === params.month && obj.day === params.day && obj.title === params.title) {
      return obj;
    }
  });
  const data = await getPostsData(obj.id);
  return {
    props: {
      postData: data,
    },
  };
}

solution ???

import type { ParsedUrlQuery } from 'querystring'
import type { GetStaticPaths, GetStaticProps } from 'next'
import type { Product } from '../types'

import { PHASE_PRODUCTION_BUILD } from 'next/constants'
import { Layout, Page, Link } from '@vercel/examples-ui'

import api from '../api'
import ProductCard from '../components/ProductCard'

interface Props {
  product: Product
}

interface Query extends ParsedUrlQuery {
  id: string
}

export const getStaticPaths: GetStaticPaths<Query> = async () => {
  const products = await api.list()

  if (process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD) {
    await api.cache.set(products)
  }

  return {
    paths: products.map((product) => ({
      params: {
        id: product.id,
      },
    })),
    fallback: 'blocking',
  }
}

export const getStaticProps: GetStaticProps<Props, Query> = async ({
  params,
}) => {
  let product = await api.cache.get(params?.id as string)

  if (!product) {
    product = await api.fetch(params?.id as string)
  }

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

  return {
    props: {
      product,
    },
  }
}

function Home({ product }: Props) {
  return (
    <Page>
      <section className="flex flex-col gap-6 items-center">
        <ProductCard product={product} />
        <Link href="/">Go back to index</Link>
      </section>
    </Page>
  )
}

Home.Layout = Layout

export default Home

https://github.com/vercel/next.js/discussions/11272?sort=top#discussioncomment-4271092

https://github.com/vercel/examples/blob/main/solutions/reuse-responses/pages/[id].tsx

refs

https://nextjs.org/learn/basics/data-fetching/implement-getstaticprops

https://www.cnblogs.com/xgqfrms/p/16934306.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(38)  评论(4编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2021-11-30 document.querySelector bug All In One
2021-11-30 js logical or assignment bug All In One
2021-11-30 ScrollToOptions All In One
2021-11-30 beats solo3 更换耳罩 All In One
2020-11-30 vue & arrow function error
2020-11-30 element-ui & babel-plugin-component config bug
2020-11-30 vue & less bug
点击右上角即可分享
微信分享提示