使用 nextjs 自定义路由?
Custom routing with nextjs?
我有一个检查路径名并对其进行操作的组件:
const router = useRouter();
const path = router.pathname;//props.location.pathname;
const p = path.split('/').filter((s) => s !== "")
let submissionId = p[0] == 's' && p[1]
const submission = useQuery(SUBMISSION, {
variables: {
id: submissionId
},
skip: submissionId === false
})
这在沼泽标准反应应用程序中工作正常,但 nextjs 重定向到 404。
有没有一种方法可以为 nextjs 设置模式以忽略 none- 存在的路由并允许组件代码处理它?
我不确定我是否理解清楚你想要什么,但如果你不想[=27=,你需要在 pages 文件夹中定义页面] 重定向到 404。但是,您可以使用 dynamic routes 来制作将执行您想要的操作的组件。
在 pages 文件夹中创建一个名为 [dynamic].js 的文件:
import React from 'react'
import { useRouter } from 'next/router'
const Dynamic = () => {
const router = useRouter();
const { dynamic } = router.query;
return (
<div>
My dynamic page slug: {dynamic}
</div>
)
}
export default Dynamic
你可以 link 像这样:
<Link href="/[dynamic]" as="/dynamic-page-slug">
<a>Link to my Dynamic Page</a>
</Link>
如果您使用的是 zeit now v2,那么您可以在此处查看 Wildcard Routes。
基本上在您的 now.json
中会有一个文件系统处理程序和一个通配符处理程序,如下所示
{
"routes": [
{ "handle": "filesystem" },
{ "src": "/.*", "status": 404, "dest": "SOME_PAGE_HERE" } // <-- this is where all the non-existent routes will be routing to
]
}
只需将 SOME_PAGE_HERE
替换为您在文件 next.config.js
中在 exportPathMap
中声明的路线。
示例:/contact
、about-us
等。
我有一个检查路径名并对其进行操作的组件:
const router = useRouter();
const path = router.pathname;//props.location.pathname;
const p = path.split('/').filter((s) => s !== "")
let submissionId = p[0] == 's' && p[1]
const submission = useQuery(SUBMISSION, {
variables: {
id: submissionId
},
skip: submissionId === false
})
这在沼泽标准反应应用程序中工作正常,但 nextjs 重定向到 404。
有没有一种方法可以为 nextjs 设置模式以忽略 none- 存在的路由并允许组件代码处理它?
我不确定我是否理解清楚你想要什么,但如果你不想[=27=,你需要在 pages 文件夹中定义页面] 重定向到 404。但是,您可以使用 dynamic routes 来制作将执行您想要的操作的组件。
在 pages 文件夹中创建一个名为 [dynamic].js 的文件:
import React from 'react'
import { useRouter } from 'next/router'
const Dynamic = () => {
const router = useRouter();
const { dynamic } = router.query;
return (
<div>
My dynamic page slug: {dynamic}
</div>
)
}
export default Dynamic
你可以 link 像这样:
<Link href="/[dynamic]" as="/dynamic-page-slug">
<a>Link to my Dynamic Page</a>
</Link>
如果您使用的是 zeit now v2,那么您可以在此处查看 Wildcard Routes。
基本上在您的 now.json
中会有一个文件系统处理程序和一个通配符处理程序,如下所示
{
"routes": [
{ "handle": "filesystem" },
{ "src": "/.*", "status": 404, "dest": "SOME_PAGE_HERE" } // <-- this is where all the non-existent routes will be routing to
]
}
只需将 SOME_PAGE_HERE
替换为您在文件 next.config.js
中在 exportPathMap
中声明的路线。
示例:/contact
、about-us
等。