如何在Next.js的页面文件夹中获取动态路由路径?
How to get dynamic route path in pages folder in Next.js?
我有一个 Layout
组件,我在其中比较路由查询和 return 根据它的布局。
我要比较动态路由,例如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>;
};
您可以使用 useRouter()
中的 pathname
,因为它包含 /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>;
};
我有一个 Layout
组件,我在其中比较路由查询和 return 根据它的布局。
我要比较动态路由,例如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>;
};
您可以使用 useRouter()
中的 pathname
,因为它包含 /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>;
};