Next.js 13 路由

huangapple go评论66阅读模式
英文:

Next Js 13 routing

问题

我如何可以使用Next Js的useRouter从"next/navigation"与应用程序路由动态添加和移除查询参数?我需要向查询添加过滤器,例如使用".../hotels?id=123&type=hotel"添加filters=219,213

我尝试使用路由器替换来添加新的查询参数。

英文:

how I can add dynamicly and remove query parameter with Next Js useRouter from "next/navigation" with App Routing?
I need add filter to query, such as add filters=219,213 with .../hotels?id=123&type=hotel

I tried router replace to add new query params

答案1

得分: 3

你需要使用 useSearchParamsusePathname 来获取 querypathname。如果你想要更新现有的历史记录而不是添加新的历史记录,你也可以使用 router.replace

'use client'

import { usePathname, useRouter, useSearchParams } from 'next/navigation'

export default function Page() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const router = useRouter()

  const updateQuery = () => {
    const newUrlParams = new URLSearchParams(searchParams.toString())
    newUrlParams.set('filters', ['219', '213'].join(','))
    router.push(`${pathname}?${newUrlParams}`)
  }

  return (
    <div>
      <button onClick={updateQuery}>Update filter</button>
    </div>
  )
}
英文:

You will need to use useSearchParams and usePathname to get query and pathname. You can also use router.replace if you want to update existing history record instead of adding new one.

&#39;use client&#39;

import { usePathname, useRouter, useSearchParams } from &#39;next/navigation&#39;

export default function Page() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const router = useRouter()

  const updateQuery = () =&gt; {
    const newUrlParams = new URLSearchParams(searchParams.toString())
    newUrlParams.set(&#39;filters&#39;, [&#39;219&#39;, &#39;213&#39;].join(&#39;,&#39;))
    router.push(`${pathname}?${newUrlParams}`)
  }

  return (
    &lt;div&gt;
      &lt;button onClick={updateQuery}&gt;Update filter&lt;/button&gt;
    &lt;/div&gt;
  )
}

huangapple
  • 本文由 发表于 2023年6月26日 03:14:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定