猫猫的内衣馆 發表於 2022-11-30 17:09:00

Next.js dynamic router path bug All In One

<h1 id="nextjs-dynamic-router-path-bug-all-in-one">Next.js dynamic router path bug All In One</h1>
<p>markdown</p>
<p>daynamic router</p>
<h2 id="bug">bug</h2>
<p>why below code not work at all ?</p>
<blockquote>
<p>dynamic router path <code>screenshot</code></p>
</blockquote>
<p><img src="https://user-images.githubusercontent.com/7291672/204731173-095ecd2f-c745-48c8-bf61-613941c6d790.png" alt="image" loading="lazy"></p>
<pre><code class="language-js">// .js

export async function getStaticPaths() {
const ids = await getPostsIds();
//   ids =
//   {
//       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}) =&gt; ({
    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,
    },
};
}
</code></pre>
<blockquote>
<p>hack way find id ✅</p>
</blockquote>
<pre><code class="language-js">
// .js

export async function getStaticPaths() {
const ids = await getPostsIds();
const paths = ids.map(({id, year, month, day, title}) =&gt; ({
    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 =&gt; {
    if(obj.year === params.year &amp;&amp; obj.month === params.month &amp;&amp; obj.day === params.day &amp;&amp; obj.title === params.title) {
      return obj;
    }
});
const data = await getPostsData(obj.id);
return {
    props: {
      postData: data,
    },
};
}
</code></pre>
<h2 id="solution-">solution ???</h2>
<pre><code class="language-ts">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&lt;Query&gt; = async () =&gt; {
const products = await api.list()

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

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

export const getStaticProps: GetStaticProps&lt;Props, Query&gt; = async ({
params,
}) =&gt; {
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 (
    &lt;Page&gt;
      &lt;section className="flex flex-col gap-6 items-center"&gt;
      &lt;ProductCard product={product} /&gt;
      &lt;Link href="/"&gt;Go back to index&lt;/Link&gt;
      &lt;/section&gt;
    &lt;/Page&gt;
)
}

Home.Layout = Layout

export default Home
</code></pre>
<p>https://github.com/vercel/next.js/discussions/11272?sort=top#discussioncomment-4271092</p>
<p>https://github.com/vercel/examples/blob/main/solutions/reuse-responses/pages/.tsx</p>
<h2 id="--反爬虫测试打击盗版️如果你看到这个信息-说明这是一篇剽窃的文章请访问-httpswwwcnblogscomxgqfrms-查看原创文章"><div id="anti-crawler" style="color: rgba(255, 0, 0, 1)"> (🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!</div></h2>
<h2 id="refs">refs</h2>
<p>https://nextjs.org/learn/basics/data-fetching/implement-getstaticprops</p>
<p>https://www.cnblogs.com/xgqfrms/p/16934306.html</p>
<hr>
<div>

</div>
<hr>
<blockquote style="display: flex; flex-flow: column; align-items: center; justify-content: center; text-align: center; border: none">
<h3><strong><span style="font-size: 16pt; color: rgba(0, 255, 0, 1)">©xgqfrms 2012-<span data-uid="copyright-aside">2021</span></span></strong>
<p><span style="font-size: 18pt; color: rgba(0, 255, 0, 1)"><strong>www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!</strong></span></p>
<p><span style="font-size: 18pt; color: rgba(0, 255, 0, 1)"><strong>原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!</strong></span></p>
</h3></blockquote>
<hr>


</div>
<div id="MySignature" role="contentinfo">
    <div style="display: flex; flex-flow: column nowrap; align-items: center; justify-content: center;">
<p>本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16939082.html</p>
<p style="color: red; font-size: 23px; margin-top: 5px; margin-botom: 5px;">未经授权禁止转载,违者必究!</P>
</div>
<hr/><br><br>
来源:https://www.cnblogs.com/xgqfrms/p/16939082.html
頁: [1]
查看完整版本: Next.js dynamic router path bug All In One