likes
comments
collection
share

Next.js中app router获取router.pathname

作者站长头像
站长
· 阅读数 162

我访问了/article/5863462212751 页面,控制台打印/article/[id],这就是我们预期的结果。现在讲解一下代码的思路。

先获取完整的URL然后获取params对象,将url转为数组变成这样['article','5863462212751'] 然后根据params中的value进行匹配,如果value和url中的元素匹配成功就置换成[${key}],代码简单,思路清晰。

代码:

import { useParams,  usePathname } from "next/navigation";

// 获取page router下的router.pathname
// https://github.com/vercel/next.js/discussions/61846

function useGetRawPath() {
  const params = useParams();
  const pathname = usePathname();
  const splittedRoute = pathname.split("/");

  if (typeof params === "object" && params !== null) {
    let reconstructedPath = "";

    for (let i = 1; i < splittedRoute.length; i++) {
      const segment = splittedRoute[i];

      // Check if the segment matches any value in the params object
      const matchingKey = Object.keys(params).find(key => params[key] === segment);

      if (matchingKey) {
        // Replace the segment with the dynamic segment
        reconstructedPath += `/[${matchingKey}]`;
      } else {
        // Keep the original segment
        reconstructedPath += `/${segment}`;
      }
    }

    return reconstructedPath;
  } else {
    // Params object is not present
    return pathname;
  }
}
export default useGetRawPath;
评论
请登录