首页 > 解决方案 > 使用 React-Router 在 ReactJS 中进行身份验证

问题描述

我有一个简单的route.js文件

const PrivateRoute = ({ component, ...rest }) => {
  const isAuthed = localStorage.getItem('Authorization')
  return (
    <Route {...rest} exact
      render = {(props) => (
        isAuthed ? (
          <div>
            {React.createElement(component, props)}
          </div>
        ) :
        (
          <Redirect
            to={{
              pathname: '/login',
              state: { from: props.location }
            }}
          />
        )
      )}
    />
  )
}
class App extends Component {
  componentWillMount() {
    if (localStorage.getItem('Authorization')) {
      history.push(`${history.location.pathname}`)
    }
  }

  render() {
    return (
      <Router history={history}>
        <div className="App-pageContainer">
          <Route exact path="/" render={() => <Redirect to="/login" />} />
          <Route path={'/login'} component={Login} />
          <PrivateRoute path={'/dashboard'} component={Dashboard} />
        </div>
      </Router>
    )
  }
}
export default App

我需要设置条件,如果用户在 localStorage( Authentication) 中有一个键,那么我想将它重定向到,/dashboard如果它不包含Authentication在 localStorage 中,那么我想将它重定向到/login.

从过去的几天开始,我完全被这个困住了。请帮忙!!!

标签: reactjsauthenticationreact-router

解决方案


我认为这类问题过于宽泛,无法回答。

但是,您可以按照这篇精彩的帖子来实现该功能。

使用 React Router v4 保护路由和身份验证

这是你完成后得到的

import React from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from 'react-router-dom'

const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true
    setTimeout(cb, 100)
  },
  signout(cb) {
    this.isAuthenticated = false
    setTimeout(cb, 100)
  }
}

const Public = () => <h3>Public</h3>
const Protected = () => <h3>Protected</h3>

class Login extends React.Component {
  render() {
    return (
      <div>
        Login
      </div>
    )
  }
}

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    fakeAuth.isAuthenticated === true
      ? <Component {...props} />
      : <Redirect to='/login' />
  )} />
)

export default function AuthExample () {
  return (
    <Router>
      <div>
        <ul>
          <li><Link to="/public">Public Page</Link></li>
          <li><Link to="/protected">Protected Page</Link></li>
        </ul>
        <Route path="/public" component={Public}/>
        <Route path="/login" component={Login}/>
        <PrivateRoute path='/protected' component={Protected} />
      </div>
    </Router>
  )
}


推荐阅读