英文:
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
你需要使用 useSearchParams 和 usePathname 来获取 query 和 pathname。如果你想要更新现有的历史记录而不是添加新的历史记录,你也可以使用 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.
'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>
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论