React使用路由跳转时控制台报Cannot update during an existing state transition (such as within `render`)错误

React使用路由跳转时控制台报Cannot update during an existing state transition (such as within render).Render methods should be a pure function of props and state.错误

这个错误是最近在使用this.props.history.replace()方法进行路由跳转,跳转之后,在控制台会产生这个错误,但对实际功能并没有影响。但是有着控制台不能有警告和错误的强迫症迫使我,仔细上网搜索了一下,发现了问题是:

因为history.push()将在render方法中引入副作用。在这种情况下,它会让 React Router 尝试开始更新 props 以反映新路径,这会触发您看到的错误。不要使用history.push(),而是使用 react-router-dom中的Redirect 。通过渲染 Redirect 组件,重定向发生在组件完成渲染之后,这意味着 React Router 所做的更新不会在渲染过程中发生。

//判断用户是否已经登录
if(!isLogin){
			//注释掉的是不使用Redirect时的代码,会报标题的错误 
            // this.props.history.replace('/login');
            // return null;
            
            //这里使用Redirect组件,错误消失
           return <Redirect to='/login'/>
        
        }else{}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
React中,可以使用react-router-dom来实现页面跳转。有几种常见的方式可以实现页面跳转。 第一种方式是使用react-router-dom中的Link组件。这种方式适用于点击按钮或其他组件进行页面跳转。具体使用方式如下: ```jsx import { Link } from 'react-router-dom'; // 在需要触发跳转的组件中 <Link to="/path/newpath">点击跳转</Link> ``` 第二种方式是使用react-router-redux中的push方法进行页面跳转。这种方式适用于在Redux中进行页面跳转。具体使用方式如下: ```jsx import { push } from 'react-router-redux'; // 在需要触发跳转的组件中,通过dispatch调用push方法 dispatch(push('/path/newpath')); ``` 第三种方式是通过配置路由来实现页面跳转。可以使用React Router来配置路由。具体代码如下: ```jsx import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; // 配置路由 <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </Switch> </Router> // 在需要触发跳转的组件中 <Link to="/about">点击跳转</Link> ``` 需要注意的是,在使用React Router进行页面跳转之前,需要先安装相关的依赖包。可以使用npm命令来安装依赖: ```bash npm install react react-dom react-scripts react-router-dom@5 --save ```<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.ToString()°

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值