简体   繁体   中英

Proper Usage of <Redirect />

After reading tutorials, I managed to work out the usage of <Redirect /> , in the code:

import React from 'react';
import Login from './Login';
import Dashboard from './Dashboard';
import {Route, NavLink, BrowserRouter, Redirect} from 'react-router-dom';

const supportsHistory = 'pushState' in window.history;

export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
            redirectToDashboard: false,
        }
    }

//-----------------------LOGIN METHODS-----------------------------
    onChangeInput(e) {
        this.setState({[e.target.name]:e.target.value});
    }
    login(e) {
        e.preventDefault();
        const mainThis = this;
        if (mainThis.state.username && mainThis.state.password) {
            fetch('APILink')
            .then(function(response) {
                response.text().then(function(data) {
                    data = JSON.parse(data);
                    if (!data.error) {
                        mainThis.setState({redirectToDashboard:true});
                    } else {
                        alert(data.msg);
                    }
                })  
            })
        } else {
            alert('Username and Password needed');
        }
    }

    renderRedirect = () => {
        if (this.state.redirectToDashboard) {
            return <Redirect exact to='/company' />
        } else {
            return <Redirect exact to='/login' />

        }
     }

    render() {
        let renderedComp;
        return(
            <BrowserRouter 
                    basename='/'
                    forceRefresh={!supportsHistory}>
                <React.Fragment>
                    {this.renderRedirect()}
                    <Route exact path="/company" render={()=><Dashboard/>} />
                    <Route exact path="/login" render={()=><Login login={(e)=>this.login(e)} onChangeInput={(e)=>this.onChangeInput(e)} />} />
                </React.Fragment>
            </BrowserRouter>
        )
    }
}

This checks what component to show based on the value of this.state.redirectToDashboard , but because of:

onChangeInput(e) {
    this.setState({
        [e.target.name]:e.target.value
    });
}

Every input re-renders the page,leaving me with:

Warning: You tried to redirect to the same route you're currently on: "/login"

I know what causes the warning, it's just that I can't think of other ways to make this work. What changes should I make or at least an idea to properly make this work?

You could wrap your Route components in a Switch which will make it so only one of its children is rendered at one time.

You could then add the redirect from / to /login as first child, and keep the redirect to /company outside of the Switch for when redirectToDashboard is true .

Example

<BrowserRouter basename="/" forceRefresh={!supportsHistory}>
  <div>
    {this.state.redirectToDashboard && <Redirect to="/company" />}
    <Switch>
      <Redirect exact from="/" to="/login" />
      <Route path="/company" component={Dashboard} />
      <Route
        path="/login"
        render={() => (
          <Login
            login={e => this.login(e)}
            onChangeInput={e => this.onChangeInput(e)}
          />
        )}
      />
    </Switch>
  </div>
</BrowserRouter>

Maybe you should not render Redirect when your condition in renderRedirect does not match.

Instead of:

renderRedirect = () => {
    if (this.state.redirectToDashboard) {
        return <Redirect exact to='/company' />
    } else {
        return <Redirect exact to='/login' />
    }
 }

you can stay there :

renderRedirect = () => {
    if (this.state.redirectToDashboard) {
        return <Redirect exact to='/company' />
    }

    return null;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM