簡體   English   中英

Next.js:一頁匹配根'/'和動態路由'/param'

[英]Next.js: one page that match root '/' and dynamic route '/param'

我有一個使用 Next.js 的單頁網站。 我在 route /上有主頁,顯示產品列表。 該頁面的代碼位於pages/index.js中。 每個產品都有一個id ,所以我可以使用/#product-id跳轉到它。

為了使它對 url 更友好,我使用product-id作為路徑中的第二個參數來復制這種行為: /product-id

我所做的只是使用useRouter()查看product-id參數:

const selectedProductId = useRouter().query['product-id']

然后使用js滾動到具有此 id 的元素:

document.getElementById(selectedProductId ).scrollIntoView()

所以我將我的腳本名稱從/pages/index.js/pages/[product-id].js

所以現在路線/1234工作已經預料到,但如果我 go 到/我得到錯誤 404。

那么有人知道如何使用一個js文件匹配//param嗎?

Nextjs 有基於文件系統的路由,所以如果你刪除/pages/index.js當然你會得到一個404錯誤。 此外/pages/index.js/pages/[product-id].js將呈現兩個單獨的頁面。

要回答您的問題,如果可以使用 nextjs 在一個文件中匹配//[productId]之類的兩條路由,我認為這是不可能的,但是通過使用特定於您的用例的淺層路由可以實現類似的結果。

因此,對於您的用例,我建議使用淺層路由,除非您想在兩個頁面中呈現相同的組件只是為了獲取product-id或想要使用 hash URL。

您可以將product-id查詢字符串參數並使用淺路由對其進行更新。 這是一個例子,

保留/pages/index.js

import { useRouter } from 'next/router';

const router = useRouter()

// when want to change the productId call
router.push('/?productId=1234', undefined, { shallow: true })

// call the scrollToView inside a useEffect hook
useEffect(() => {
    const productId = router.query.productId
    // get the element using the productId above then call scrollIntoView()
})

// if using useEffect with the dependency router.query.productId, 
// when you change the productId once and scroll up and try to change to the same -
// productId again it will not scroll to view, hence not using the dependency array
// at all

解釋更多關於淺層路由的作用

淺層路由將允許更改 URL 而無需再次運行數據獲取方法,即getStaticPropsgetServerSideProps 這將使更新的查詢和路徑名可用,而無需更改 state。 閱讀更多關於它的 nextjs 文檔

選項 1:提取共享代碼

您可以將 Page 組件提取到單獨的文件中,然后將其同時導入/pages/index.js/pages/[product-id].js ,因此代碼不會重復。

選項 2:使用實驗性rewrites功能

假設您有/pages/[product-id].js您可以在用戶請求/時顯示此頁面。

您需要添加next.config.js

module.exports = {
  experimental: {
    async rewrites() {
      return [
        { source: "/", destination: "/[product-id]" },
      ];
    }
  }
}

因此,當用戶請求/他們會看到/[product-id]的內容,只是帶有空的產品 ID。

請注意,目前 rewrite 不支持自動渲染動態頁面,因此您必須禁用動態頁面的自動渲染

您可以通過將getServerSideProps添加到/pages/[product-id].js來做到這一點。

export async function getServerSideProps() {
  return {
    props: {},
  }
}

可選捕獲所有路線

通過將參數包含在雙括號 ([[...slug]]) 中,可以使捕獲所有路由成為可選的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM