reactjs - this.props.history.push 超出了最大更新深度
问题描述
我正在尝试为我的 Web 应用程序设置登录注册路由。
这个想法是:
登录并注册
如果没有身份验证,它将直接指向
/login
哪个将呈现Login
组件。有的话我会直接/dashboard
- 在
Login
中,如果用户输入正确的用户名和密码,它将重定向到/dashboard
,否则它不会对路由做任何事情。 - 如果用户访问
/
如果有任何认证,用户将重定向到/dashboard
else 到/login
我曾尝试使用在-组件this.props.history.push
之间进行重定向。Login
DashBoard
到目前为止,这是我的路线,我不知道这是否是最佳实践。如果不是,任何帮助将不胜感激。
路由.js:
...
render() {
return(
<>
<Route path="/login"><Login showAlert={this.showAlert}/></Route>
<Route path="/register"><Register showAlert={this.showAlert}/></Route>
<AuthRoute authed={AuthenticationService.isUserLoggedIn()} path="/">
<Dashboard/>
</AuthRoute>
<AuthRoute authed={AuthenticationService.isUserLoggedIn()} path="/dashboard">
<Dashboard/>
</AuthRoute>
</>
)
...
登录.js:
...
componentDidMount() {
if(AuthenticationService.isUserLoggedIn()) {
this.props.history.push('/dashboard');
}
}
...
handleSubmit = (event) => {
event.preventDefault();
AuthenticationService.authenticateAccount(this.state.email, this.state.password)
.then(() => {
this.props.history.push('/dashboard')
});
}
...
export default withRouter(Login);
但是,它Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
虽然我使用componentDidMount()
同样,任何帮助将不胜感激。
谢谢。
更新:问题只发生在点击login
后/login
解决方案
通过将路由器位置与我尝试进行的推送进行比较,我能够逃脱此循环,如下所示:
import { withRouter, useHistory, useLocation } from 'react-router-dom';
//...
const App = () => {
//...
const history = useHistory();
const location = useLocation();
const changePage = (change: { page: string, params: string, refresh: boolean}) => {
if (location.pathname !== change.page || location.search !== change.param) {
history.push({
pathname: change.page,
search: change.param
});
};
if (change.refresh) {
history.go(0);
};
};
//...
};
export default withRouter(App);
推荐阅读
- kubernetes - 使用 kubectl 命令获取数据中心
- c++ - 64位模块映射到内存时如何查找函数表?
- docker - 将调试器附加到 docker 内的应用程序
- python - 分组和添加大型数据框 python pandas
- laravel-5.4 - 使用 laravel 5.4 在 MySql 中将数据作为数组插入
- azure - 如何替换 VSTS CD 版本中的 json 文件?
- opayo - MySagePay 退款时出现 4020 错误
- protractor - 量角器:获取 Aria 标签
- php - CakePHP 3 自定义验证:如何在编辑期间将新值与旧值进行比较?
- c++ - 无法让 FastNoise 用于草地补丁