未捕获的恒定违规:超出最大更新深度...等等。刷新页面时错误消失

时间:2019-04-27 18:27:48

标签: reactjs react-router react-router-dom

enter image description here

此问题似乎重复,但并非如此。我理解该错误,并且已经解决了此类错误,但这次我无法弄清是什么导致了无限循环。

这是导致错误的react组件的代码:

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import './Login.scss';
import axios from 'axios';
import { endPoint } from '../App/path';
import { logIn, isLoggedIn } from '../App/TokenStore';

const re = /^[a-zA-Z0-9_-]{3,15}$/;
class Login extends Component {
  constructor() {
    super();
    this.state = {
      username: '',
      password: '',
      errorMessage: 'Please Login to proceed!',
    };
  }

  onUserNameChange = (e) => {
    this.setState({ username: e.target.value });
  }

  onPasswordChange = (e) => {
    this.setState({ password: e.target.value });
  }

  onFormSubmit = (event) => {
    event.preventDefault();
    const { username, password } = this.state;
    const { history } = this.props;

    const isUserNameValid = re.test(String(username).toLowerCase());
    if (isUserNameValid) {
      axios.post(`${endPoint}/login.json`, { username, password })
        .then((response) => {
          if (response.status === 200) {
            if (response.statusText === 'OK') {
              this.setState({
                username: '', password: '', errorMessage: '',
              });
              if (response.config.data) {
                console.log(response);
                logIn(response.config.data, 'response.config.data.password');
                history.push('/dashboard');
              } else {
                throw new Error();
              }
            } else {
              this.setState({ errorMessage: 'Please enter valid credential!' });
            }
          }
        }).catch((err) => {
          if (err.response) {
            this.setState({ errorMessage: 'Please enter valid username!' });
          } else {
            this.setState({ errorMessage: 'Unknown Error!!' });
          }
        });
    } else {
      this.setState({ errorMessage: 'Please enter valid username!' });
    }
  }

  render() {
    if (isLoggedIn()) {
      return <Redirect to="/dashboard" />;
    }
    const {
      username, password, errorMessage,
    } = this.state;
    return (
      <div className="Login">
        <form className="Form" onSubmit={this.onFormSubmit}>
          <p className="errorMessage">{errorMessage}</p>
          <div className="form__group">
            <label id="username" className="Label" htmlFor="username">
              <i className="fa fa-user" />
              <b>Username</b>
            </label>
            <input
              value={username}
              onChange={e => this.onUserNameChange(e)}
              id="username"
              type="username"
              placeholder="Your username"
              required
            />
          </div>
          <div className="form__group">
            <label id="password" className="Label" htmlFor="password">
              <i className="fa fa-key" />
              <b>Password</b>
            </label>
            <input
              value={password}
              onChange={e => this.onPasswordChange(e)}
              id="password"
              type="password"
              placeholder="Your Password"
              required
            />
          </div>
          <button type="submit" className="Btn">LOGIN</button>
        </form>
      </div>
    );
  }
}


Login.propTypes = {
  history: PropTypes.shape(),
};
Login.defaultProps = { history: {} };

export default Login;

这些是我在上述组件中使用的其他功能:

export const logIn = (username, token) => {
  sessionStorage.setItem('username', username);
  sessionStorage.setItem('loggedIn', true);
  sessionStorage.setItem('token', token);
};

export const isLoggedIn = () => Boolean(sessionStorage.getItem('loggedIn'));

这是仪表板组件

import React from 'react';
import { NavLink } from 'react-router-dom';
import './Dashboard.scss';

const dashboard = () => (
  <div className="container">
    <div className="row">
      <div className="card col-5 mr-auto ml-auto">
        <h5 className="card-header">Lorem ipsum</h5>
        <div className="card-body">
          <h5 className="card-title">Lorem ipsum</h5>
          <p className="card-text">Lorem ipsum</p>
          <NavLink to="/dashboard/VRlist" className="btn btn-dashboard">Update/Delete</NavLink>
        </div>
      </div>
      <div className="card col-5 mr-auto ml-auto">
        <h5 className="card-header">Lorem ipsum</h5>
        <div className="card-body">
          <h5 className="card-title">Lorem ipsum</h5>
          <p className="card-text">Lorem ipsum</p>
          <NavLink to="/dashboard/registration" className="btn btn-dashboard"> Registration</NavLink>
        </div>
      </div>
    </div>
  </div>
);

export default dashboard;

这是我的主要应用程序组件

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Navbar from './Navbar/Navbar';
import Login from './Login/Login';
import Dashboard from './Dashboard/Dashboard';
import { isLoggedIn } from './App/TokenStore';
import VRlist from './VRlist/VRlist';
import NewRegistration from './newRegistration/newRegistration';
import UpdateRegistration from './updateRegistration/updateRegistration';

const App = () => {
  if (!isLoggedIn()) {
    return (
      <div>
        <Navbar />
        <Route component={Login} />
      </div>
    );
  }
  return (
    <div>
      <Navbar />
      <Switch>
        <Route exact path="/" component={Login} />
        <Route path="/dashboard/VRlist/edit/:id" component={UpdateRegistration} />
        <Route path="/dashboard/VRlist" component={VRlist} />
        <Route path="/dashboard/registration" component={NewRegistration} />
        <Route path="/dashboard" component={Dashboard} />
        <Route component={Login} />
      </Switch>
    </div>
  );
};

export default App;

现在,当我运行应用程序并进行登录时,此错误仅在当前选项卡中的第一次登录时才会发生,如果刷新页面,该错误将消失。

1 个答案:

答案 0 :(得分:0)

显然,我使用了react-router和react-router-dom版本5,这是在调用history.push()时导致无限渲染循环的原因,但是对于其余组件'history.push( )'工作正常,但登录页面。尽管切换到版本4.3.1完全发出了问题。