下一页.js:一个匹配根"/"和动态路由"/参数"的页面



我有一个网站作为单个页面,正在使用Next.js。我在路线/上有显示产品列表的主页。此页面的代码位于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工作的路线已经预期,但如果我去/,我会收到错误 404。

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

可选捕获所有路由

捕获所有路由可以通过将参数包含在双括号中来成为可选的([[...蛞蝓]](。

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

解释浅层路由的作用

浅层路由将允许在不运行数据获取方法(即再次getStaticPropsgetServerSideProps(的情况下更改 URL。这将使更新的查询和路径名可用,而无需更改状态。阅读更多关于它 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为空。

请注意,目前重写不支持自动呈现的动态页面,因此您必须禁用动态页面的自动呈现

您可以通过向/pages/[product-id].js添加getServerSideProps来做到这一点。

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

最新更新