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

Ave*_*man 11 javascript single-page-application reactjs next.js

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

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

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

NextJS版本:Next 9.5.3

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

示例网址:

http://localhost:3000/kpop-heroes
Run Code Online (Sandbox Code Playgroud)

页面功能示例:

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>
  )
};
Run Code Online (Sandbox Code Playgroud)

渲染:

路径名呈现文件名,而不是 URL 中键入的单词

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

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

Gab*_* H. 18

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

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

const router = useRouter();

router.asPath
Run Code Online (Sandbox Code Playgroud)


Jer*_*yal 5

要获取这两种情况的正确 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;
  }
Run Code Online (Sandbox Code Playgroud)


bcj*_*ohn 0

我认为正确的方法是在特定的(例如/twitter)下定义动态路由。path

渲染页面路径:

/pages/twitter/[keywords].jsx
Run Code Online (Sandbox Code Playgroud)

示例网址:

http://localhost:3000/twitter/kpop-heroes
Run Code Online (Sandbox Code Playgroud)

在url的第一级定义dynamic-route是不合理的。