简体   繁体   English

React-router 动态 URL 不包括特定的 URL

[英]React-router dynamic URL that excludes specific URL

I want to make a dynamic url for /:user that does not run in certain urls.我想为 /:user 制作一个动态 url ,它不在某些网址中运行。 Since /:user is linked to base, it runs for every route I made.由于 /:user 链接到基础,它运行在我所做的每条路线上。 Is there a way to exclude specific url routes?有没有办法排除特定的 url 路线? I purposely DO NOT want to make url handles like /user/:userid to fix this issue.我故意不想让 url 像 /user/:userid 这样的句柄来解决这个问题。

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.您可以制作一个Private 路由组件,您可以在其中传递一个确保您通过身份验证的方法。

isAuthenticate Method isAuthenticate 方法

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

PrivateRoute.js PrivateRoute.js

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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