You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js应用首页加载时router.query为空 如何正确获取URL参数

Next.js pages路由下获取URL查询参数为空的解决方法

问题原因

Next.js pages 路由的页面在首次渲染时,客户端路由还未完成水合,此时router.isReady状态为false,router.query会返回空对象,只有水合完成后才会填充正确的查询参数。

解决方案

方案1:客户端侧监听路由就绪状态

通过useEffect监听router.isReady状态,等路由完成水合后再读取查询参数即可:

import Head from 'next/head'
import { useRouter } from 'next/router';
import { useEffect } from 'react';

export default function Home () {
  const router = useRouter()

  useEffect(() => {
    // 路由就绪后再读取query
    if(router.isReady) {
      const param = router.query.param
      console.log('query:', param) // 输出12345
      // 如果需要把参数传递给iframe,可以在这里拼接src属性
      // const iframe = document.getElementById('typeform-full')
      // iframe.src = `https://form.typeform.com/to/xxxxx?typeform-medium=embed-snippet&param=${param}`
    }
  }, [router.isReady, router.query])

  return (
    <div>
      <Head>
        <meta name="viewport"
              content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
        <title>My Title</title>
        <link rel="apple-touch-icon" sizes="180x180"
              href="/apple-touch-icon.png"/>
        <link rel="icon" type="image/png" sizes="32x32"
              href="/favicon-32x32.png"/>
        <link rel="icon" type="image/png" sizes="16x16"
              href="/favicon-16x16.png"/>
        <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"/>
        <meta name="msapplication-TileColor" content="#da532c"/>
        <meta name="theme-color" content="#ffffff"/>
      </Head>
      <body>
      <iframe id="typeform-full" width="100%" height="100%" frameBorder="0"
              allow="camera; microphone; autoplay; encrypted-media;"
              src="https://form.typeform.com/to/xxxxx?typeform-medium=embed-snippet"/>
      <script type="text/javascript"
              src="https://embed.typeform.com/embed.js"/>
      </body>
    </div>
  )
}

方案2:服务端侧直接获取参数

如果需要页面首次渲染就拿到参数,不需要等待客户端水合,可以通过getServerSideProps在服务端直接读取参数并传递给组件:

import Head from 'next/head'

// 服务端读取查询参数
export async function getServerSideProps(context) {
  const param = context.query.param || null
  return {
    props: {
      param
    }
  }
}

export default function Home ({ param }) {
  console.log('query:', param) // 首次渲染就可以拿到12345
  return (
    // 原有页面结构不变
    <div>
      {/* 原有内容 */}
    </div>
  )
}

内容的提问来源于stack exchange,提问作者chuckieDub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:57:01