在NextJS动态路由中没有获取被点击组件的ID

hiz5n14c  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(107)

顾名思义,我似乎不能在我的项目中弄清楚动态路由。我有一个Home组件(这是我的项目的主页),我从外部API获取数据,并使用map显示它们。基本上,我想做的是:当用户点击任何产品项时,应重定向到相应的products/:[id]页面。
我使用next/Link中的Link实现了动态路由。但是在我的products/[id].jsx文件中,我似乎无法捕获单击产品的id
下面是我的Home组件代码:

'use client'

import Product from "@/components/product"
import { useQuery } from "@tanstack/react-query"
import axios from "axios"
import Link from "next/link"

const Home = () => {

  const {data,isLoading,error} = useQuery({
    queryKey: ['products'],

    queryFn: async () => {
      const res = await axios.get(
        'https://fakestoreapi.com/products'
      )
      const data = await res.data
      if(data){
        console.log(data);
        return data
      }
    }
  })

  if(isLoading) return "Your content is Loading..."

  if(error) return "There was an error" + error.message

  if(data){
    
    // Organize and sort the data based on categories
      const organizedData = data ? data.reduce((acc, item) => {
        const category = item.category;
        if (!acc[category]) {
          acc[category] = []
        }
        acc[category].push(item)
        return acc
    }, {})
    : {}

    return(
      <section className='flex-col'>
      <div className="bg-black w-full flex flex-col justify-center items-center text-yellow-100 h-[45vh] sm:h-[55vh] mt-8">
        <h1 className='text-5xl'>OnlineStore</h1>
        <h2 className='text-xl'>Buy Everything you need</h2>
      </div>
      <section className="padding p-8"> 
        <h2>Discover Our Products</h2>
        {Object.entries(organizedData).map(([category, categoryData]) => (
          <div key={category} className="py-5">
            <h3 className="uppercase text-xl">{category}</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 place-items-center gap-8 mt-5">
            {categoryData.map((product)=> {
              return(
                  <Link key={product.id} href={`products/${product.id}`}>
                    <Product
                      key={product.id} 
                      id= {product.id}
                      img={product.image} 
                      title={product.title} 
                      price={product.price}
                    />
                  </Link>
              )
            })}
            </div>
          </div>
        ))}
      </section>
    </section>
    )
  }
  return null
}

export default Home

字符串
这是我的[id].jsx代码

'use client'

import { useRouter } from "next/navigation";

const ProductPage = () => {
  const router = useRouter()
  const { id } = router.push
  console.log(id)

  return(
    <div>
      <h1>Product Details</h1>
      <p>Product ID: {id}</p>
    </div>
  )

}

export default ProductPage;


有人能看看这个,告诉我我做错了什么吗?

ivqmmu1c

ivqmmu1c1#

您可以通过在[id].jsx文件中解构它来获取参数,如下所示:

'use client'

import { useRouter } from "next/navigation";

const ProductPage = ({params}) => {
  const router = useRouter()
  const { id } = params
  console.log(id)

  return(
    <div>
      <h1>Product Details</h1>
      <p>Product ID: {id}</p>
    </div>
  )

}

export default ProductPage;

字符串

相关问题