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

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

我有一个URL喜欢

bar?id=foo

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

但是如果我直接转到浏览器中的路由,查询字符串不会通过。

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
}

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

useRouter() 是一个 React Hook,因此它只会 run/update 在客户端上。

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

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