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{}