【发布时间】: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