我正在尝试使用 React 和 Node.js 构建登录表单,但重定向和路由对我不起作用。
我在 App.js 中设置了路由,并调用了一个组件来验证所有变量并需要重定向到管理页面或用户页面。 我的问题是重定向。 如果我重定向,我会收到“超出最大更新深度”错误,如果我路由,则页面为空白。
//App.js:
<BrowserRouter>
<div className="App">
<CheckLogin/> {/*Validation component */}
<Route exact path="/" component={Login}/>
<Route path="/admin" component={AdminHome}/>
<Route path="/user" component={UserHome}/>
</div>
</BrowserRouter>
//CheckLogin.js:
state={
UserDataFromDB:{},
}
componentDidMount=()=>
{
if (this.state.UserDataFromDB.ans)
{
console.log('there is ans');
}
else
{
axios.get(`http://localhost:4000/CheckLogin`, { withCredentials: true })
.then(response => {
// this.setState({ Cookie: response.data.id });
this.setState({ UserDataFromDB: response.data })
})
.catch(error => {
console.log("error: ", error);
})
}
}
RouteSomewhere()
{
if(this.state.UserDataFromDB.ans==0)
{
return <Redirect to='/'/>
}
if (this.state.UserDataFromDB.role==1)
{
return<Redirect to="/admin"/>
}
if (this.state.UserDataFromDB.role==0)
{
return <Redirect to="/user"/>
}
}
render() {
return (
<div className="CheckLogin">
{this.RouteSomewhere()}
</div>
);
}
}
我预计该页面将重定向到另一个页面。现在我收到“超出最大更新深度”错误。
谢谢:)
最佳答案
简短回答 - 在重定向之前检查路线。
长答案 - 发生这种情况是因为您的 <CheckLogin/>
组件每次与您的应用程序一起渲染。每次运行时都是如此 {this.RouteSomewhere()}
无论它在哪里。
而且因为它不是每次都重新安装,所以内部状态保持不变,这导致了下一个重定向,这导致了下一个渲染,然后下一个重定向......然后你就陷入了循环。
那么,你应该做什么 - 或者添加检查是否在所需的 URL 上,如果是 - 停止进行重定向,
//CheckLogin.js:
state={
UserDataFromDB:{},
isRedireted: false,
}
componentDidUpdate() {
const targetURL = this.getRedirectURL();
if (window.location.pathname === targetURL && !this.state.isRedireted) {
this.setState({
isRedireted: true;
})
}
}
getRedirectURL(UserDataFromDB) {
if (UserDataFromDB.ans==0) {
return '/';
} else if (UserDataFromDB.role==1) {
return '/admin';
} else if (UserDataFromDB.role==0) {
return '/user';
}
return null;
}
RouteSomewhere() {
if (this.state.isRedireted) { // If we already there - do nothing
return null;
}
return <Redirect to={this.getRedirectURL(this.state.UserDataFromDB)} />;
}
或在 axios.get 回调中以编程方式重定向(请参阅 Programmatically navigate using react router V4 获取示例)。
componentDidMount=()=> {
if (this.state.UserDataFromDB.ans) { // On mount you won't have anythig here, so this code is always skipped.
console.log('there is ans');
} else {
axios.get(`http://localhost:4000/CheckLogin`, { withCredentials: true })
.then(response => {
cosnt redirectURL = this.getRedirectURL(response.data);
if (redirectURL) {
history.push(redirectURL);
}
})
.catch(error => {
console.log("error: ", error);
})
}
}
关于javascript - 路由时如何避免 "Maximum update depth exceeded"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56450462/