首页 > 解决方案 > 如何在 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>;
};

标签: javascriptroutesnext.js

解决方案


您可以使用pathnamefrom 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>;
};

推荐阅读