我试图将用户重定向到搜索结果,但 router.push() 显然不起作用。我将 url 更改为不存在的页面,并且路线发生了变化,但是当涉及到使用已创建的页面的 url 时,没有任何反应。
我尝试做这样的事情,但它也不起作用。
import { useRouter } from 'next/router';
const router = useRouter();
const search = () => {
router.push('/search');
};
}
如果您使用Nextjs13,请注意从
useRouter
导入next/navigation
:
❌ import { useRouter } from 'next/router';
至:
✅ import { useRouter } from 'next/navigation';
这里的解决方案是通过执行以下操作来防止默认功能:
import { useRouter } from 'next/router';
const router = useRouter();
const Search = (e) => {
e.preventDefault()
router.push("/search");
};
只需将其替换为 window.location.href = "/"
从 next js 13 开始 use router 应该从 next/navigation
导入✅ import { useRouter } from 'next/navigation';
调用 router.push 来更新浅层路由(例如:更新客户端上的查询参数)可能会导致页面重新加载。使用本机 API (window.history) 来处理它们。
window.history.pushState(null, '', `?${...YOUR_QUERY_PARAMS}`)
或
window.history.replaceState(null, '',NEW_PATH)
参考https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating