我在 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]);
我在控制台中看到的只是路径名
参数,而不是查询字符串参数。所以如果我访问:
.../123/456?q=something&order=date
注销的查询
对象仅是:
{articleId: '某事', pageNum: '456' }
这意味着,当我们创建保留查询字符串参数的“后退”按钮时,我们返回的 URL 中包含无法识别的值,并且所有应用的过滤器都会丢失。从根本上说,我错过了一些有值(value)的信息 - 为什么查询字符串参数没有通过?
在 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
对象没有我需要的内容.
最佳答案
回复迟了,但仍然 -
router
有一个变量 isReady
,当从服务器端渲染时(这是第一次加载),该变量保持 false。从下一次加载开始,它变为 true 并开始提供查询
。
因此要使用它,我们必须应用useEffect
const router = useRouter();
React.useEffect(() => {
if (router.isReady) {
// Code using query
console.log(router.query);
}
}, [router.isReady]);
关于reactjs - 下一个/路由器不返回组件中的查询字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70368145/