mirror of
https://github.com/hanzoai/next.js.git
synced 2026-10-30 14:46:38 +00:00
### Why? The issue was brought up when the app had rewrites (say `/ -> /foo`), and the page used `useRouter.push/replace` to add the search queries; it used the destination's pathname (`/foo?query=1`) instead of just adding the query (`/?query=1`). Current Behavior: https://github.com/vercel/next.js/actions/runs/16647831682/job/47112716254?pr=82236#step:34:156 ### How? Therefore, as we handle the hash (`#`), if the target path only needs a query `?`, we may use `router.asPath` by default for static routes to resolve cases with rewrites. However, if it is a dynamic route, it needs to be able to interpolate the query (for `/[id]` segment, `/?id=1` interpolates to `/1` route), so use `router.pathname`. Finally, if it is suspected to be a rewritten path, use `router.asPath`. **Note:** There is an edge case where the pathname is dynamic, and also a rewrite path to the same segment. E.g. in `/[slug]` path, rewrite `/foo -> /bar` In this case, it will be treated as a non-rewritten path and possibly interpolate the query string. E.g., `/any?slug=foo` will become the content of `/foo`, not rewritten as `/bar`. This is currently a trade-off of not resolving rewrite paths on every Router/Link call, but using a lighter route regex pattern check. Fixes https://github.com/vercel/next.js/issues/81476
35 lines
594 B
TypeScript
35 lines
594 B
TypeScript
import Link from 'next/link'
|
|
import { useRouter } from 'next/router'
|
|
|
|
export default function Page() {
|
|
const router = useRouter()
|
|
|
|
function handlePush() {
|
|
router.push({
|
|
query: {
|
|
param: 1,
|
|
},
|
|
})
|
|
}
|
|
|
|
function handleReplace() {
|
|
router.replace({
|
|
query: {
|
|
param: 1,
|
|
},
|
|
})
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<button id="router-push" onClick={handlePush}>
|
|
router.push
|
|
</button>
|
|
<button id="router-replace" onClick={handleReplace}>
|
|
router.replace
|
|
</button>
|
|
<Link href="?param=1">Link</Link>
|
|
</>
|
|
)
|
|
}
|