繁体   English   中英

如何使用 Next.js 中的查询字符串参数进行路由?

[英]How do I route with query string params in Next.js?

我有一个 URL 之类的

bar?id=foo

如果我通过router.push('bar?id=foo')路由到这个,一切正常。

但是如果我 go 在浏览器中直接指向路由,则查询字符串不会通过。

const BarComponent = ()=>{
    console.log(useRouter())
}

这输出

ServerRouter {
  route: '/bar',
  pathname: '/bar',
  query: {},
  asPath: '/bar',
  basePath: '',
  events: undefined,
  isFallback: false,
  locale: undefined,
  isReady: false,
  locales: undefined,
  defaultLocale: undefined,
  domainLocales: undefined,
  isPreview: false,
  isLocaleDomain: false
}

那就是您从服务器在终端上获得的 output ,并显示其默认值( {} )。 在客户端上,您应该看到 2 个控制台日志:第一个带有空查询 object(来自 SSR),第二个带有您的查询字符串。

useRouter()是一个 React Hook,因此它只会在客户端上运行/更新。

如果您想访问服务器端的查询字符串,您需要使用getServerSideProps并通过上下文 object 中的query参数访问它。

export async function getServerSideProps({ query }) {
    console.log(query) // `{ id: 'foo' }`
    //...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM