【问题标题】:next/router not returning query string params in component下一个/路由器未在组件中返回查询字符串参数
【发布时间】:2022-07-14 22:10:44
【问题描述】:

我在 Next.js 的动态路由中的页面内有一个组件,它需要读取 URL 查询字符串参数。该应用包含一系列可供您搜索的文章,您可以通过访问相应的 URL 访问文章中的特定“页面”。

所以我在文件结构中有一个pages 路由:

/pages -> /article -> /[articleId] -> [pageNum].tsx

[pageNum].tsx 启用了 SSR,即它包含一个 getServerSideProps 函数。

当用户执行搜索时,搜索参数保存在查询字符串中,即?q=something&order=date...。但是,在有问题的组件中,如果我执行以下操作:

const router = useRouter();

useEffect(() => {
  if (!router.isReady) return;
  console.log(router.query);
}, [router]);

我在控制台中看到的只是pathname 参数,而不是查询字符串参数。所以如果我访问:

.../123/456?q=something&order=date

已注销的 query 对象只是曾经:

{ articleId: 'something', pageNum: '456' }

这意味着,当我们创建一个保留查询字符串参数的“返回”按钮时,我们返回的 URL 中包含无法识别的值,并且所有应用的过滤器都会丢失。从根本上说,我错过了一些有价值的信息——为什么查询字符串参数没有通过?

useEffect 之外注销路由器对象会显示:

asPath: "/article/article_100000/2?q=iceland"
back: ƒ ()
basePath: ""
beforePopState: ƒ ()
components: {/article/[articleId]/[pageNum]: {…}, /_app: {…}, /search/[start]/[size]: {…}}
defaultLocale: undefined
domainLocales: undefined
events: {on: ƒ, off: ƒ, emit: ƒ}
isFallback: false
isLocaleDomain: false
isPreview: false
isReady: true
locale: undefined
locales: undefined
pathname: "/article/[articleId]/[pageNum]"
prefetch: ƒ ()
push: ƒ ()
query:
  pageNum: "2"
  articleId: "article_100000"
[[Prototype]]: Object
reload: ƒ ()
replace: ƒ ()
route: "/article/[articleId]/[pageNum]"

可以使用 asPath 属性并从其上剔除部分以获得所需的东西,但我不明白为什么 query 对象没有我需要的东西。

【问题讨论】:

  • 只有第一次渲染是这样吗?你是用nextjs的路由器还是react?
  • 如果我注销useEffect,浏览器中的控制台重复使用pathname 参数记录相同的对象,似乎每次渲染都会发生这种情况。这是nextjs 路由器。
  • 您能否在执行 console.log(router) 时添加到问题中得到什么
  • 添加了更多日志记录
  • @mattlock 你找到解决方案了吗?我也遇到了同样的问题。

标签: reactjs next.js next-router


【解决方案1】:

回复晚了,但还是 -

router 有一个变量isReady 在从服务器端渲染时保持为假,这是第一次加载。从下一次加载开始,它变为 true 并开始提供 query

所以要使用这个,我们必须申请useEffect

const router = useRouter();
React.useEffect(() => {
    if (router.isReady) {
        // Code using query
        console.log(router.query);
    }
}, [router.isReady]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2012-05-29
    • 2015-12-22
    • 2017-09-01
    • 2016-09-21
    相关资源
    最近更新 更多