使用Next.js Router在Next.js中创建自定义URL

lqfhib0f  于 2023-08-04  发布在  其他
关注(0)|答案(3)|浏览(110)

我正在使用应用程序目录结构开发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模式的问题。
请求帮助:
我将感谢任何帮助,指导或建议,如何正确地实现这个自定义的URL模式使用Next.js路由器在我的应用程序目录结构。谢谢你,谢谢

kiayqfof

kiayqfof1#

在itemDetail页面中,您需要执行以下操作:

import { useSearchParams } from "next/navigation";

const Index = () => {
  const searchParams = useSearchParams();
  const search = searchParams.get("search");

  return <div>{search}</div>;
}

字符串
https://nextjs.org/docs/app/api-reference/functions/use-search-params
如果你想知道更多,这是这个函数的文档链接。

vcirk6k6

vcirk6k62#

这是我的解决方案

// 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;

字符串

xpcnnkqh

xpcnnkqh3#

@ugur_sa我删除了[id]文件夹,并将里面的页面.tsx移动到itemDetail中,并且正在工作!
Thanks!

相关问题