首页 > 解决方案 > this.props.history.push 超出了最大更新深度

问题描述

我正在尝试为我的 Web 应用程序设置登录注册路由。

这个想法是:

我曾尝试使用在-组件this.props.history.push之间进行重定向。LoginDashBoard

到目前为止,这是我的路线,我不知道这是否是最佳实践。如果不是,任何帮助将不胜感激。

路由.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

标签: reactjsreact-router-v4

解决方案


通过将路由器位置与我尝试进行的推送进行比较,我能够逃脱此循环,如下所示:

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);


推荐阅读