简体   繁体   中英

ReactJs protected route redirect/refresh issue

Using react + react-router-dom :

import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom'; 

And protecting a route by this:

Router

const Router = () => {
    return (
        <Switch>
            <PrivateRoute exact path='/Panel' component={Panel}></PrivateRoute>
            <Route exact path='/Register' component={Register}></Route>
            <Route exact path='/Login' component={Login}></Route>
        </Switch>
    );
};

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route
        {...rest}
        render={props =>
            Auth.getAuth() ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: "/Login"
                    }}
                />
            )
        }
    />
);

Auth

const Auth = {
    isAuthenticated: false,
    authenticate() {
        this.isAuthenticated = true;
    },
    signout() {
        this.isAuthenticated = false;
    },
    getAuth() {
        return this.isAuthenticated;
    }
};

So this working fine and user easily can login, logout, but the problem is when user logged I want to redirect user to /Panel route so I tried:

window.location.href = "/Panel"

OR:

this.props.history.push('/Panel')

Both redirect to /Login again too fast, but If I click on Panel link it going to Panel route. Second problem is when I refresh page on this address /Panel it bring me back to /Login again. So what I want to solve are:

  1. How to redirect to protected route?
  2. How to avoid redirect when refresh page on protected route? If I type this address and enter it not working too.

Already seen this topic and tried but no success:

What is the best way to redirect a page using React Router?

For the first question:

You can keep the url in the state like this so that after login you can redirect to.

<Redirect
  to={{
    pathname: "/login",
    state: { from: props.location }
  }}
/>

And in Login component, after successfull login you can redirect to:

const { state } = this.props.location;
window.location = state ? state.from.pathname : "/";

For the second question:

one alternative solution would be keeping the login state in localStorage so that after refreshes the app can read from there. This is generally done sending a jsonwebtoken from login api to the client, and saving the token to the localStorage.

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