Реагирует на причины переадресации: максимальная глубина обновления превышена - PullRequest
0 голосов
/ 03 мая 2019

В приложении React у меня есть страница входа. Когда пользователь успешно аутентифицирован, приложение должно перенаправить на другую страницу. Но между страницей входа и другой страницей возникает пинг-понг, что приводит к сообщению об ошибке браузера: «Превышена максимальная глубина обновления.»

Я использую Ionic 4, но я думаю, что это не влияет на описанное поведение.

Login page:
import React, { Component } from 'react'
import { IonContent, IonGrid, IonRow, IonCol, IonItem, IonLabel, IonButton, IonInput} from '@ionic/react'
import { Redirect } from 'react-router'
import './LoginPage.css'

class LoginPage extends Component {
  state = {
  uid: localStorage.getItem('userid'),
  pw: '',
  token: '',
  msg: '',
  isAuthenticated: false
  }

  handleSubmit (e: any) {
e.preventDefault();

if (this.state.uid !== '' && this.state.pw === ' ') {   
  this.setState({isAuthenticated: true});
}
else {
  this.setState({token: ''});
  this.setState({pw: ''});
  this.setState({msg: 'Login error.'});
}
  };

  handleChange(e: any) {
e.preventDefault();
this.setState({[e.target.name]: e.target.value });  
  }


  render() {    
const isAuth = this.state.isAuthenticated;

if (isAuth === true) {
  return (
    <Redirect to="/anotherpage"/>
  )
} else {
    return (
<IonContent>
      <form onSubmit={(e) => this.handleSubmit(e)} action="/selectmodel">
        <IonGrid fixed>
          <IonRow justify-content-center>
            <IonCol align-self-center padding>
              <div className="header">
                <h1>Compoot</h1>
                <span>Version 0.1</span>
              </div><br /><br />
              <IonItem>
                <IonLabel position="floating">User Name</IonLabel>
                <IonInput name="uid" value={this.state.uid} type="text" required={true} clearInput={true} onIonBlur={(e) => this.handleChange(e)} ></IonInput>
              </IonItem><br />

              <IonItem>
                  <IonLabel position="floating">Password</IonLabel>
                  <IonInput name="pw" value={this.state.pw}  type="password" required={true} clearInput={true} onIonBlur={(e) => this.handleChange(e)}></IonInput>
              </IonItem><br />
              <div className="msg">
                {this.state.msg ? (this.state.msg): null}
              </div><br />
              <div className="login">
                <IonButton size="large" type="submit" >Login</IonButton>
              </div>
              <br /><br />
              <div className="link">
                <IonLabel onClick={this.showResetPW}>
                  Forgot password
                </IonLabel>
              </div>

            </IonCol>
          </IonRow>
        </IonGrid>
      </form>
    </IonContent>


);
}
  }
}

export default LoginPage;

Другая страница:

import React, { Component } from 'react';
import { IonContent} from '@ionic/react'


class SelectModelPage extends Component {


  render() {
console.log('selectmodel');
return (
  <IonContent>
    <div>This is SelectModel!</div>
  </IonContent>
);
  }
    }

export default SelectModelPage;

App.tsx:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route,  } from 'react-router-dom';

import { IonApp, IonPage, IonRouterOutlet } from '@ionic/react';

import './App.css';

import LoginPage from './LoginPage';
import SelectModelPage from './SelectModelPage';


class App extends Component {
  render() {
    return (
  <Router>
    <div className="App">
      <IonApp>
        <IonPage id="main">
          <IonRouterOutlet>
            <Route exact path="/selectmodel" component={SelectModelPage} />
            <Route exact path="/"  component={LoginPage} />
          </IonRouterOutlet>
        </IonPage>
      </IonApp>
    </div>
  </Router>
);
  }
    }

    export default App;

Есть идеи?

1 Ответ

0 голосов
/ 03 мая 2019

Вам не хватает Switch в определении вашего маршрута:

<Router>
    <div className="App">
      <IonApp>
        <IonPage id="main">
          <IonRouterOutlet>
            <Switch>
              <Route exact path="/selectmodel" component={SelectModelPage} />
              <Route exact path="/"  component={LoginPage} />
            </Switch>
          </IonRouterOutlet>
        </IonPage>
      </IonApp>
    </div>
  </Router>

Дополнительная информация: https://reacttraining.com/react-router/core/api/Switch

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...