简体   繁体   English

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

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

I have a URL like我有一个 URL 之类的

bar?id=foo bar?id=foo

If I route to this via router.push('bar?id=foo') everything works fine.如果我通过router.push('bar?id=foo')路由到这个,一切正常。

But if I go direct to the route in the browser, the query string does not get passed through.但是如果我 go 在浏览器中直接指向路由,则查询字符串不会通过。

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

This outputs这输出

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
}

That's the output you get on the terminal from the server, and shows its default value ( {} ).那就是您从服务器在终端上获得的 output ,并显示其默认值( {} )。 On the client, you should see 2 console logs: first one with an empty query object (from SSR) and a second one with your query string in it.在客户端上,您应该看到 2 个控制台日志:第一个带有空查询 object(来自 SSR),第二个带有您的查询字符串。

useRouter() is a React Hook so it'll only run/update on the client. useRouter()是一个 React Hook,因此它只会在客户端上运行/更新。

If you want to have access to the query string on the server-side, you'll need to use getServerSideProps and access it through the query param from the context object.如果您想访问服务器端的查询字符串,您需要使用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