使用react-router-dom的<Navigate>组件时出现最大更新深度超限警告求助
解决React Router 组件导致的最大更新深度超出问题
问题原因
你遇到的Maximum update depth exceeded警告,核心原因有两点:
- 点击按钮触发
submit将navi设为true后,组件渲染<Navigate>触发路由跳转,但组件未卸载,navi状态始终为true;路由跳转后组件重新渲染,再次触发<Navigate>,形成无限循环,最终导致更新深度超出限制。 - 代码存在结构错误:
submit方法定义在组件外部,导致this指向异常,绑定逻辑也不正确。
修复方案
方案1:编程式导航(类组件推荐)
类组件中优先使用编程式导航替代声明式<Navigate>,从根源避免循环问题:
import { withRouter, RouteComponentProps } from "react-router-dom"; import React from "react"; import { Button } from '你的组件库路径'; interface MyComponentState {} // 通过withRouter注入路由属性 class MyComponent extends React.Component<RouteComponentProps> { constructor(props) { super(props); this.state = {}; // 正确绑定submit的this指向 this.submit = this.submit.bind(this); } submit() { // 直接调用history.push实现跳转 this.props.history.push("/navigation/newpage"); } render() { return ( <div> <div> <Button onClick={this.submit}>提交</Button> </div> </div> ); } } // 用withRouter包裹组件以获取路由相关属性 export default withRouter(MyComponent);
方案2:修复声明式导航的循环问题(不推荐类组件使用)
如果坚持使用<Navigate>,需确保跳转后立即重置navi状态:
import { Navigate } from "react-router-dom"; import React from "react"; import { Button } from '你的组件库路径'; interface MyComponentState { navi: boolean; } export default class MyComponent extends React.Component { constructor(props) { super(props); this.state = { navi: false, }; this.submit = this.submit.bind(this); } submit() { this.setState({ navi: true }); } render() { if (this.state.navi) { // 跳转后立即重置状态,避免重复渲染Navigate this.setState({ navi: false }); return <Navigate to="/navigation/newpage" />; } return ( <div> <div> <Button onClick={this.submit}>提交</Button> </div> </div> ); } }
关键注意点
- 类组件中优先选择编程式导航,逻辑更清晰,能规避声明式导航带来的循环风险。
- 组件内方法必须正确绑定
this,避免因指向错误导致状态更新失败。
内容的提问来源于stack exchange,提问作者Shreya
相关产品推荐
相关产品推荐

