查看: 65|回覆: 0

Next.js dynamic router path bug All In One

[複製鏈接]

2

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2010-11-17
發表於 2022-11-30 17:09:00 | 顯示全部樓層 |閲讀模式

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

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

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, 禁止转载 🈲️,侵权必究⚠️!


回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部