使用React-Router在ReactJS中进行身份验证

时间:2018-09-29 07:49:29

标签: reactjs authentication react-router

我有一个简单的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)中有密钥,那么如果它在localStorage中不包含/dashboard,我想将其重定向到Authentication然后我要将其重定向到/login

过去几天,我对此一无所知。请帮忙!!!

1 个答案:

答案 0 :(得分:2)

我认为这类问题太笼统了。

但是,您可以关注这篇精彩的博文,以实现该功能。

Protected routes and authentication with 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>
  )
}