javascript - 如何在 Next.js 的 pages 文件夹中获取动态路由路径?
问题描述
我有一个Layout
组件,我在其中比较路由查询并根据它返回布局。
我想比较动态路由,例如invoices/invoice-1
我目前有以下组件,但如您所见,configArrays.includes(pathname)
它不起作用。
const config = {
layout1: ['/invoices/[id]'],
layout2: ['/route/sign-in'],
};
const Layout = ({ children }) => {
const { asPath } = useRouter();
const url = new Url(asPath, true);
const pathname = url.pathname;
if (config.layout1.includes(pathname)) {
return <Layout1>{children}</Layout1>;
}
if (config.layout2.includes(pathname)) {
return <Layout1>{children}</Layout1>;
}
return <DefaultLayout>{children}</DefaultLayout>;
};
解决方案
您可以使用pathname
from useRouter()
,因为它包含页面的路径/pages
,而不是 URL 中的实际路径。这允许您匹配动态路由,例如/invoices/[id]
.
const Layout = ({ children }) => {
const { pathname } = useRouter();
if (config.layout1.includes(pathname)) {
return <Layout1>{children}</Layout1>;
}
if (config.layout2.includes(pathname)) {
return <Layout2>{children}</Layout2>;
}
return <DefaultLayout>{children}</DefaultLayout>;
};
推荐阅读
- php - Laravel Passport 如何从 php 代码管理客户端
- reactjs - 在扩展通用 State/Prop 中反应类更改
- authentication - 在 slapd.conf 文件中加密的密码
- microsoft-graph-api - OneDrive 文件下载返回 95 字节内容
- bash - Bash 脚本比较结合 getfattr
- airflow - 如何通过 Airflow 中的 task_id 获取上游任务的任务实例?
- postgresql - 为什么我在此加入时收到此 PostgreSQL 错误...?
- javascript - 在 Google Chrome 开发工具中,对象前面的字母是什么意思?
- azure - Azure 应用程序配置:labelFilter:是否可以“首选”某个标签而不排除其他标签?
- reactjs - 转到上一页下一个js应用程序时不显示数据