You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS 12.2路由异常:Link刷新页面、router.push无响应求助

解决方案
  • 确保正确导入Next.js自带的Link组件,而非其他路由库:
    import Link from 'next/link'
    
  • 如果Link内部包裹的不是原生<a>标签(比如按钮、div等),必须添加passHref属性,否则会触发页面硬刷新:
    <Link href="/" passHref>
      <span>首页</span>
    </Link>
    
  • 避免在Link或其子元素上手动设置window.location.href,这会覆盖Next.js的客户端路由逻辑。

针对router.push('/login')无响应的问题

  • 确保正确获取路由实例,使用Next.js的useRouter钩子(仅支持函数组件/自定义钩子):
    import { useRouter } from 'next/router'
    
    const Layout = () => {
      const router = useRouter()
    
      const goToLogin = () => {
        router.push('/login')
      }
    
      return (
        <button type="button" onClick={goToLogin}>登录</button>
      )
    }
    
  • 若在类组件中使用路由,需用withRouter高阶组件包裹:
    import { withRouter } from 'next/router'
    import React from 'react'
    
    class Layout extends React.Component {
      goToLogin = () => {
        this.props.router.push('/login')
      }
    
      render() {
        return <button type="button" onClick={this.goToLogin}>登录</button>
      }
    }
    
    export default withRouter(Layout)
    
  • 检查/login页面是否在pages目录下正确创建(Next.js 12.x基于Pages Router,页面文件路径需与路由路径匹配)。
  • 排查是否有其他事件处理函数调用了event.preventDefault(),阻止了按钮的点击逻辑执行。

内容的提问来源于stack exchange,提问作者Tom L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:11:02