简体   繁体   English

PrivateRoute 在 reactjs react-router-dom 中不起作用

[英]PrivateRoute not working in reactjs react-router-dom

I am completely stuck when integrating PrivateRoute HOC in my react.js project.在我的 react.js 项目中集成PrivateRoute HOC 时,我完全陷入困境。

Here is my route file这是我的路线文件

import React, { Component } from "react";
import { Route, Redirect, Switch, BrowserRouter as Router } from 'react-router-dom';
import Dashboard from "../view/Dashboard/Dashboard";
import Login from "../view/Login/Login";
import Admin from "../view/UserManagement/Admin";
import cookie from 'react-cookies'

const PrivateRoute = ({ component, ...rest }) => {
  const isAuthed = cookie.load('token')
  console.log(isAuthed, 'dddddddddddddddddddd')
  return (
    <Route {...rest} exact
      render = {(props) => (
        isAuthed ? (
          <div>
            {React.createElement(component, props)}
          </div>
        ) :
        (
          <Redirect
            to={{
              pathname: '/login',
              state: { from: props.location }
            }}
          />
        )
      )}
    />
  )
}

class MainPanel extends Component {

  render() {
    return (
      <div style={{ direction: direction }}> 
        <Router>
          <Switch>
            <Route path="/login" component={Login}/>
            <PrivateRoute path="/" component={Dashboard} />
            <PrivateRoute path="/AdminManagement" component={Admin} />
           </Switch>
        </Router>
      </div>
    )
  }
}
export default withNamespaces('common') (MainPanel);

I am totally break my head with this but didn't get rid out of that issue.我完全打破了我的头脑,但没有摆脱这个问题。 Why my console inside the PrivateRoute doesn't show the values为什么我在PrivateRoute内的控制台不显示值

Is there any issue with the react and react-router-dom versions react 和 react-router-dom 版本有什么问题吗

Thank you in advance!!!先感谢您!!!

The PrivateRoute component that you have is correct, You however only need to re-order your Routes for them to work correctly.您拥有的PrivateRoute组件是正确的,但是您只需要重新排序您的Routes即可正常工作。 /AdminManagement route should come before / since Switch renders the first matching Route and a Route path will also match its prefix path /AdminManagement路由应该在/之前,因为 Switch 呈现第一个匹配的路由并且Route path也将匹配其前缀路径

class MainPanel extends Component {

  render() {
    return (
      <div style={{ direction: direction }}> 
        <Router>
          <Switch>
            <Route path="/login" component={Login}/>
            <PrivateRoute path="/AdminManagement" component={Admin} />
            <PrivateRoute path="/" component={Dashboard} />
           </Switch>
        </Router>
      </div>
    )
  }
}
export default withNamespaces('common') (MainPanel);

Working demo工作演示

Here is how I handle my private routes, maybe it will help you also.这是我处理我的私人路线的方式,也许它也会对您有所帮助。 I have protectedRoutes as an array with the routes.我将protectedRoutes作为一个包含路由的数组。 you can fit them as you like.你可以随心所欲地安装它们。

 const routes = [ { path: '/login', exact: true, name: 'Login', component: Login, }, ]; const protectedRoutes = [ { path: '/admin', exact: true, name: 'Admin', component: Admin, }, ];

 <Switch> {routes.map((route, idx) => (route.component ? ( <Route key={idx} path={route.path} exact={route.exact} name={route.name} render={props => ( <route.component {...props} /> )} /> ) : (null)))} {protectedRoutes.map((route, idx) => (route.component ? ( <Route key={idx} path={route.path} exact={route.exact} name={route.name} render={props => ( isAuth ? <route.component {...props} /> : <Redirect to="/login" /> )} /> ) : (null)))} </Switch>

LE: added full example based on the original code LE:添加了基于原始代码的完整示例

 import React, { Component } from 'react'; import { Route, Redirect, Switch, BrowserRouter as Router } from 'react-router-dom'; import Dashboard from '../view/Dashboard/Dashboard'; import Login from '../view/Login/Login'; import Admin from '../view/UserManagement/Admin'; import cookie from 'react-cookies'; const routes = [ { path: '/login', exact: true, name: 'Login', component: Login, }, ]; const protectedRoutes = [ { path: '/', exact: true, name: 'Dashboard', component: Dashboard, }, { path: '/AdminManagement', exact: true, name: 'Admin', component: Admin, }, ]; class MainPanel extends Component { constructor(props) { super(props); this.state = { isAuthed: cookie.load('token'), }, }; render() { const { isAuthed } = this.state; return ( <div style={{ direction: direction }}> <Router> <Switch> {routes.map((route, idx) => (route.component ? ( <Route key={idx} path={route.path} exact={route.exact} name={route.name} render={props => ( <route.component {...props} /> )} /> ) : (null)))} {protectedRoutes.map((route, idx) => (route.component ? ( <Route key={idx} path={route.path} exact={route.exact} name={route.name} render={props => ( isAuth ? <route.component {...props} /> : <Redirect to="/login" /> )} /> ) : (null)))} </Switch> </Router> </div> ) } } export default withNamespaces('common')(MainPanel);

try change library to react-cookie ;尝试将库更改为react-cookie

let PrivateRoute = ({ component: Component, cookies, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      cookies.get("name") ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

https://codesandbox.io/s/015k0jl0ql https://codesandbox.io/s/015k0jl0ql

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

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