簡體   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