我正在开发一个具有应用程序目录结构的 Next.js 应用程序。在我的应用程序中,我有一个名为 itemDetail 的页面,用于显示特定项目的详细信息。但是,我想自定义 URL,使其看起来像 /items?search=[id] 而不是默认的 /itemDetail/[id]。
我尝试在 next.config.js 中使用 Next.js Router 的 rewrites() 函数,如下所示:
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/items?search=:id',
destination: '/itemDetail/:id',
},
];
},
};
在我的 itemList 页面中,我使用以下链接导航到 itemDetail 页面:
// itemList.tsx
import Link from 'next/link';
// Inside the component
<Link href={`/items?search=${item.id}`} >{item.title}</Link>
预期结果:
我预计当我访问自定义 URL /items?search=[id] 时,它会正确重定向到具有相应项目 ID 的 itemDetail 页面。但是,重定向没有按预期工作,并且我遇到了自定义 URL 模式的问题。
请求帮助:
对于如何在我的应用程序目录结构中使用 Next.js Router 正确实现此自定义 URL 模式,我将不胜感激。谢谢!
这是我的解决方案
// itemList.tsx
import Link from 'next/link';
// Inside the component
<Link href={{ pathname: '/itemDetail', query: { search: item.id } }}>
{item.title}
</Link>
// itemDetail.tsx
import { useRouter } from 'next/router';
const ItemDetail = () => {
const router = useRouter();
const { search } = router.query;
// Use the search parameter to display the details of the item
return (
<div>
<h1>Item Details:</h1>
<p>Search: {search}</p>
{/* Display the details of the item */}
</div>
);
};
export default ItemDetail;