router.push() 没有按预期工作 NextJS

问题描述 投票:0回答:4

我试图将用户重定向到搜索结果,但 router.push() 显然不起作用。我将 url 更改为不存在的页面,并且路线发生了变化,但是当涉及到使用已创建的页面的 url 时,没有任何反应。

我尝试做这样的事情,但它也不起作用。

import { useRouter } from 'next/router';
const router = useRouter();

const search = () => {
    router.push('/search');
    };
}
reactjs next.js router
4个回答
15
投票

如果您使用Nextjs13,请注意从

useRouter
导入
next/navigation

❌ import { useRouter } from 'next/router';

至:

✅ import { useRouter } from 'next/navigation';

文档链接


6
投票

这里的解决方案是通过执行以下操作来防止默认功能:

import { useRouter } from 'next/router';
const router = useRouter();

const Search = (e) => {
        e.preventDefault()
        router.push("/search");
    };

2
投票

只需将其替换为 window.location.href = "/"


0
投票

从 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

© www.soinside.com 2019 - 2024. All rights reserved.