NextJS:动态 router.pathname 不显示路径,而是显示文件名 - 如何获取路径中的单词?

Posted

技术标签:

【中文标题】NextJS:动态 router.pathname 不显示路径,而是显示文件名 - 如何获取路径中的单词?【英文标题】:NextJS: dynamic router.pathname does not show path, but filename - how to get words in path? 【发布时间】:2021-01-20 13:42:01 【问题描述】:

我将这个示例尽可能简单,如果需要更多信息来解决,我可以稍后包含更多代码

我在 nextJS 中使用动态路由。我的应用根据通过 API 使用 twitter-v2 包输入动态路由的关键字从 twitter 中提取结果

我正在尝试使用router.pathname 的路径中的单词来在页面上创建一些属性,但它使用文件名而不是 url 中的单词。

NextJS 版本:Next 9.5.3

渲染页面路径:/pages/[keywords].jsx

示例网址:

http://localhost:3000/kpop-heroes

示例页面功能:

import Router from 'next/router'

export default function Keywords() 
  const router = useRouter();

  const KEYWORDS = router.pathname
    .slice(1)
    .split('-')
    .join(' ');

  return (
   <div>Twitter reactions to <code>KEYWORDS</code></div>
  )
;

渲染:

我误解了这个功能吗?是否可以检索 url 中的单词而不是文件名?

注意:我一直使用window.location.href 作为解决方法,但我的理解是访问窗口对象不是最佳的

【问题讨论】:

【参考方案1】:

使用asPath 属性。它返回浏览器中显示的路径(包括查询)。

https://nextjs.org/docs/api-reference/next/router#router-object

const router = useRouter();

router.asPath

【讨论】:

【参考方案2】:

我只是使用了错误的方法——正确的方法是router.query

考虑以下网址:

http://localhost:3000/test-keywords?query=params,%20strings,%20other%20things&anotherLevel=more%20stuff

记录方法产生的对象:

  const router = useRouter();
  console.log(router.query);

输出:

  
    anotherLevel: "more stuff"
    keywords: "test-keywords"
    query: "params, strings, other things"
  

我一定忽略了它,它显然在此处的文档中:https://nextjs.org/docs/routing/dynamic-routes

我想我会留下这个,以防其他人也对此感到困惑

【讨论】:

【参考方案3】:

为这两种情况获取正确的 URL,例如动态([slug])和固定路径:

const router = useRouter();

let relativeURL = "";

  const slug = router.query.slug;
  if (slug) 
    relativeURL = router.pathname.replace("[slug]", slug as string);
   else 
    relativeURL = router.pathname;
  

【讨论】:

【参考方案4】:

我认为正确的方法是在特定的 path 下定义 dynamic-routes(例如 /twitter)。

渲染页面路径:

/pages/twitter/[keywords].jsx

示例网址:

http://localhost:3000/twitter/kpop-heroes

在url的第一级定义动态路由是不合理的。

【讨论】:

我一直在使用第一级就好了(?)。我认为它是否在子目录中并不重要。在“警告”下nextjs.org/docs/routing/dynamic-routes 说:预定义路线优先于动态路线,动态路线优先于捕获所有路线。我个人在 pages 目录中只有 index.jsx,其他默认为 [keywords].jsx

以上是关于NextJS:动态 router.pathname 不显示路径,而是显示文件名 - 如何获取路径中的单词?的主要内容,如果未能解决你的问题,请参考以下文章

next js 中基于路由的条件组件渲染

Amazon CloudFront 中的 NextJS 动态路由

nextjs用静态类名添加动态类名[重复]

Nextjs 中使用 getServerSideProps 进行动态路由

NextJS:如何在根处理多个动态路由

NEXTJS - 公共图像未显示在动态路线上