简体   繁体   中英

Redirect to server route on ReactJS component using React Router V4

I have my React Router V4 routes structured this way:

const isAuthenticated = () => {
    let hasToken = localStorage.getItem("jwtToken");
    if (hasToken) return true;
    return false;
};

const AuthenticatedRoute = ({ component: Component, ...rest }) =>
    <Route
        {...rest}
        render={props =>
            isAuthenticated()
                ? <Component {...props} />
                : <I NEED TO REDIRECT FROM HERE TO SERVER PAGE />}
    />;

class App extends Component {
    render() {
        return (
            <BrowserRouter basename="/editor">
                <Switch>
                    <AuthenticatedRoute exact path="/" component={AppNav} />
                    <AuthenticatedRoute
                        exact
                        path="/:module"
                        component={AppNav}
                    />
                    <AuthenticatedRoute
                        exact
                        path="/:module/:screen"
                        component={AppNav}
                    />
                    <AuthenticatedRoute
                        exact
                        path="/:module/:screen/:action"
                        component={AppNav}
                    />
                    <AuthenticatedRoute
                        exact
                        path="/:module/:screen/:action/:id"
                        component={AppNav}
                    />

                    <Route component={PageNotFoundError} />
                </Switch>
            </BrowserRouter>
        );
    }
}

export default App;

As you see on code, if not authenticated I want to redirect to server page. The page is another react application to manage user registration and is located in the server but in another route tree: /registration

What I've tried with no success:

<Redirect to="//registration' />
windows.location = "/registration"
windows.location.href = "/registration"
<Redirect to="http//registration' />
windows.location = "http://registration"
windows.location.href = "http://registration"

All of the redirects to page in current application.

What would be the solution for this ?

I implemented it like so:

const AuthenticatedRoute = ({ component: Component, ...rest }) =>
    (<Route
        {...rest}
        render={props =>(
            isAuthenticated()
                ? (<Component {...props} />)
                : ( window.location = "http://your_full_url" )
        )}
    />);

I had a create-react-app project with react router, and the problem that when entering a path '/path/*' it loaded the as if in the same react router, even though I had configuration for using another react project with an express server. The problem was that the service worker was running in the background, and for any route inside '/' it was using cache.
The solution for me was to modify the 'registerServiceWorker.js', so that when you are inside the path, you ignore the service worker. I didn't get too deep in learning about service workers, but here is the code I used:

export default function register() {
    ...
    window.addEventListener('load', () => {
        const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
        if(window.location.href.match(/*\/path\/*/)){
           // Reload the page and unregister if in path
           navigator.serviceWorker.ready.then(registration => {
              registration.unregister().then(() => {
                  window.location.reload();
              });
           });
        } else if (isLocalhost) {
    ...

When inside the path, it unsubscribes the service worker and reloads the page.

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