【问题标题】:How do I route with query string params in Next.js?如何在 Next.js 中使用查询字符串参数进行路由?
【发布时间】:2021-03-26 16:30:09
【问题描述】:

我有一个类似的网址

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
}

【问题讨论】:

    标签: javascript next.js next-router


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我猜这是一个菜鸟问题:(
    • 有效的问题,经常会产生混淆。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 2017-09-01
    • 2014-08-23
    相关资源
    最近更新 更多