【问题标题】:How to get dynamic route path in pages folder in Next.js?如何在 Next.js 的 pages 文件夹中获取动态路由路径?
【发布时间】:2021-08-29 16:14:36
【问题描述】:

我有一个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>;
};

【问题讨论】:

    标签: javascript routes next.js


    【解决方案1】:

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

    【讨论】:

    • 谢谢胡里奥。它按预期打印出/invoices/[id]
    猜你喜欢
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-05
    • 2022-11-12
    • 1970-01-01
    相关资源
    最近更新 更多