javascript React Router v4 Auth

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript React Router v4 Auth相关的知识,希望对你有一定的参考价值。

//Usage
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import Route from './AuthRoute';

import Login from './Login';
import Private from './Private';

export default () => 
  <Router>
    <div>
      <Route component={ Login } path="/login" />
      <Route component={ Private } path="/private" />
    </div>
  </Router>;
import React from 'react';
import PropTypes from 'prop-types';
import { Redirect, Route } from 'react-router-dom';

//Mock of an Auth method, can be replaced with an async call to the backend. Must return true or false
const isAuthenticated = () => true;

const PRIVATE_ROOT = '/private';
const PUBLIC_ROOT = '/login';

const AuthRoute = ({component, ...props}) => {
  const { isPrivate } = component;
  if (isAuthenticated()) {
    //User is Authenticated
    if (isPrivate === true) {
      //If the route is private the user may proceed.
      return <Route { ...props } component={ component } />;
    }
    else {
      //If the route is public, the user is redirected to the app's private root.
      return <Redirect to={ PRIVATE_ROOT } />;
    }
  }
  else {
    //User is not Authenticated
    if (isPrivate === true) {
      //If the route is private the user is redirected to the app's public root.
      return <Redirect to={ PUBLIC_ROOT } />;
    }
    else {
      //If the route is public, the user may proceed.
      return <Route { ...props } component={ component } />;
    }
  }
};

AuthRoute.propTypes = {
  component: PropTypes.oneOfType([
    PropTypes.element,
    PropTypes.func
  ])
};

export default AuthRoute;
import React from 'react';

export default class Login extends React.Component {

  static isPrivate = false

  render() {
    return <h1>{' Login '}</h1>;
  }
}
import React from 'react';

export default class Private extends React.Component {

  static isPrivate = true

  render() {
    return <h1>{' Private '}</h1>;
  }
}

以上是关于javascript React Router v4 Auth的主要内容,如果未能解决你的问题,请参考以下文章

javascript React Router v4 Auth

javascript React Router路由更改侦听器

javascript 使用React Router v4的多个布局

javascript 使用react-router将Props传递给组件

服务器渲染-React Router Dom V^5.2.0 Error: Invariant failed: Browser history needs a DOM

使用 React-Native-Router-Flux 在 React Native 中嵌套场景