Next.js:匹配根“/”和动态路由“/param”的页面

joh*_*pin 5 javascript reactjs next.js

我有一个使用 Next.js 的单页面网站。我的路线主页/显示了产品列表。该页面的代码位于pages/index.js. 每个产品都有一个,id所以我可以使用 跳转到它/#product-id

为了使其更加 url 友好,我使用作为product-id路由中的第二个参数来复制此行为,如下所示:/product-id

我所做的只是product-id使用以下命令查看参数useRouter()

const selectedProductId = useRouter().query['product-id']
Run Code Online (Sandbox Code Playgroud)

然后使用以下命令滚动到具有此 id 的元素js

document.getElementById(selectedProductId ).scrollIntoView()
Run Code Online (Sandbox Code Playgroud)

所以我将脚本名称从 更改/pages/index.js/pages/[product-id].js.

所以现在路线/1234工作已预期,但如果我去的话,/我会收到错误 404。

那么有人知道我如何匹配//param使用一个js文件吗?

sub*_*tra 1

Nextjs 有基于文件系统的路由,所以如果你删除/pages/index.js当然你会得到一个404错误。还将/pages/index.js呈现/pages/[product-id].js两个单独的页面。

为了回答您的问题,如果可以使用 nextjs 在一个文件中匹配两个路由,例如//[productId],我认为这是不可能的,但是通过使用特定于您的用例的浅层路由可以实现类似的结果。

因此,对于您的用例,我建议使用浅层路由,除非您想在两个页面中呈现相同的组件只是为了获取product-id或想要使用哈希 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
Run Code Online (Sandbox Code Playgroud)

详细解释浅层路由的作用

浅层路由将允许更改 URL,而无需再次运行数据获取getStaticProps方法getServerSideProps。这将使更新的查询和路径名可用,而无需更改状态。阅读更多有关nextjs 文档