小编And*_*pin的帖子

如何使用新的应用程序路由器访问 Next.js 13.4 中的查询参数?

我正在使用最新版本的 Next.js (13.4) 和新的应用程序路由器。

在我的应用程序中,我有一个 Link 组件,其按钮位于 ../components/products.tsx 文件中。

每个产品都有一个“详细信息”按钮,可使用“链接”组件导航到动态路线。我使用链接组件的路径名和查询属性来传递查询参数和路由。

以下是 ../components/products.tsx 文件中 Link 组件的示例:

<Link href={{
                  pathname:`product/${item._id}`,
                  query:{
                    _id: item._id,
                    title: item.title,
                    description: item.description,
                    oldPrice: item.oldPrice,
                    price: item.price,
                    brand: item.brand,
                    image: item.image,
                    isNew: item.isNew,
                    category: item.category,
                  },
                }}
                as ={`product/${item._id}`}
                >
Run Code Online (Sandbox Code Playgroud)

在路径为 app/product/[id] 的动态路由组件 (page.tsx) 中,我想访问查询参数并将它们呈现在页面上。以下是 page.tsx 文件的示例:

import React from 'react';
import { useRouter } from 'next/router';

const ProductPage = () => {
  const router = useRouter();
  const query = router.query;

  return (
    <div>
      <h1>Product Details</h1>
      <p>ID: {query._id}</p> …
Run Code Online (Sandbox Code Playgroud)

query-string next.js next-router nextjs-dynamic-routing next.js13

6
推荐指数
1
解决办法
2万
查看次数