javascript - Next.js:匹配根 '/' 和动态路由 '/param' 的页面

标签 javascript reactjs next.js

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

为了使它对 url 更友好,我使用 product-id 复制了这种行为。作为 route 的第二个参数:/product-id .

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

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

然后使用 js 滚动到具有此 ID 的元素:

document.getElementById(selectedProductId ).scrollIntoView()

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

所以现在路线/1234预计工作,但如果我去 /我收到错误 404。

所以有人知道我如何匹配//param使用一个 js文件?

最佳答案

Nextjs 有基于文件系统的路由,所以如果你删除 /pages/index.js当然你会得到一个404错误。还有/pages/index.js/pages/[product-id].js将呈现两个单独的页面。
要回答您的问题,是否可以匹配两条路线,例如 //[productId]在使用 nextjs 的一个文件中,我认为这是不可能的,但是通过使用特定于您的用例的浅层路由可以实现类似的结果。
因此,对于您的用例,我建议使用浅路由,除非您想在两个页面中呈现相同的组件只是为了获得 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
解释更多关于浅层路由的作用
浅路由将允许在不运行数据获取方法的情况下更改 URL,即 getStaticPropsgetServerSideProps再次。这将使更新的查询和路径名可用而不更改状态。了解更多信息 nextjs docs .

关于javascript - Next.js:匹配根 '/' 和动态路由 '/param' 的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62100121/

相关文章:

javascript - this.setState() 无法正常处理绑定(bind)事件

javascript - 如何从 JSON 文件在 Gatsby 中创建页面?

javascript - i18n 支持与下一次导出不兼容。 (SSR - NextJS 10)

javascript - 在 Next.js 中重用 getStaticProps

javascript - 将多页应用程序转换为单页

javascript - 在 vue 中的特定元素中向下滚动

javascript - JavaScript 中的 try-catch : how to get stack trace or line number of the original error

javascript - ReactJS API 数据获取 CORS 错误

javascript - 表示没有设置Cookie

javascript - 将文本区域的部分字符串(HTML 代码)替换为/n 换行符