简体   繁体   中英

React-router dynamic URL that excludes specific URL

I want to make a dynamic url for /:user that does not run in certain urls. Since /:user is linked to base, it runs for every route I made. Is there a way to exclude specific url routes? I purposely DO NOT want to make url handles like /user/:userid to fix this issue.

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route } from "react-router-dom";
import { createBrowserHistory } from "history";
import { AuthProvider } from '../src/components/provider/AuthProvider.js';
import Register from '../src/views/Register';
import Login from '../src/views/Login';
import Admin from '../src/views/Admin';
import User from '../src/views/User';
import App from './App';
import './assets/scss/style.scss';

const history = createBrowserHistory();

ReactDOM.render(
  <AuthProvider>
    <Router history={history}>
      <App />
      <Route path="/register" component={Register} />
      <Route path="/login" component={Login} />
      <Route path="/admin" component={Admin} />
      <Route path="/:user" component={User} />
    </Router>
  </AuthProvider>,
  document.getElementById('root')
);

const User = ({ match, location }) => {
  let load = true;
  if (location.pathname === '/admin' || location.pathname === '/login' || location.pathname === '/register') {
    load = false;
  }
  return (
    <React.Fragment>
      {load && 
        <h1>this is user {match.params.user}'s page</h1>
      }
    </React.Fragment>
  )
}

export default User;

You can make a Private route component in which you can pass a method which makes sure you are authenticated.

isAuthenticate Method

export const isAuthenticated = () => {
if(typeof window === undefined){
    return false;
} 
if(localStorage.getItem("jwt")){
    return JSON.parse(localStorage.getItem("jwt"));
}else{
    return false;
}
}

PrivateRoute.js

const PrivateRoute = ({component:Component, ...rest}) => {
return <Route
    {...rest}
    render={props=>
        isAuthenticated()?(<Component {...props}/>
        ):(
        <Redirect
            to={{
                pathname:"/login",
                state:{ from:props.location }
            }}
        /> 
        )}
/>
}

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