Next.js 13电子商务动态路由

vlf7wbxs  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(174)

我目前的电子商务有动态路由。网址有以下模式:
产品列表页

/en-us/categoryLevel1
/en-ca/categoryLevel1
/en-uk/categoryLevel1/categoryLevel2

产品详情页

/en-us/categoryLevel1/abc-1234567788
/en-ca/categoryLevel1/abcdesf-121122113
/fr-fr/categoryLevel1/abcabc-1111111

类别名称是动态的。
如何构建我的Next.js项目以匹配所有URL?

qyyhg6bp

qyyhg6bp1#

pages文件夹中,您可以创建以下结构:

pages/
  [lang]/
    [category]/
      index.jsx
      [sub]/
       [product]/
        index.jsx

然后在相应的文件(index.jsx)中,你可以使用useRouternext/router来获取变量:

import { useRouter } from 'next/router'
export default function index(){
  const router = useRouter()
  const {id} = router.query //this is [lang], [category] and [sub]
  ...code
}

可以在这里看到更多:https://nextjs.org/docs/routing/dynamic-routes

编辑:

要在index.jsx中检索Product数据,只需获取URL传递的产品ID(例如:/en-us/categoryLevel1/abc-12345678),然后加载它:

import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'

export default function Index(){
  const router = useRouter()
  const {id} = router.query //this is [lang], [category] and [sub]
  const [product, setProduct] = useState(null)

  const loadProduct = async function (id) {
    // for exemple...
    const res = await fetch(`/api/product/${id}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
    const response = await res.json()
    setProduct(response)
  
    return response
  }
  
  useEffect(() => {
    loadProduct(id)
  }, [id])

  return (
    <div>
      {/* HTML */}
      {product && product.name}
    </div>
  )
}

相关问题