我有一个网站作为使用 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,即
getStaticProps
或 getServerSideProps
再次。这将使更新的查询和路径名可用而无需更改状态。阅读更多相关信息 nextjs docs .
关于javascript - Next.js:匹配根 '/' 和动态路由 '/param' 的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62100121/