import React from 'react';
import PropTypes from 'prop-types';
import {Route,Redirect,withRouter} from 'react-router-dom';
import LoginUser from 'service/LoginUser'; //私有路由,只有登录的用户才能访问
class PrivateRoute extends React.Component{
constructor(props) {
super(props);
this..state = {
isAuth : _loginUser.hasLogin();
}
}
componentWillMount(){
if(!isAuth){
const {history} = this.props;
setTimeout(() => {
history.replace("/login");
}, 1000)
}
}
render(){
const { component: Component,path="/",exact=false,strict=false} = this.props;
return this.state.isAuth ? (
<Route path={path} exact={exact} strict={strict} render={(props)=>( <Component {...props} /> )} />
) : <Authenricated />;
}
}
PrivateRoute.propTypes ={
path:PropTypes.string.isRequired,
exact:PropTypes.bool,
strict:PropTypes.bool,
component:PropTypes.func.isRequired
}
export default withRouter(PrivateRoute);

使用redux:

import { Component } from 'react'
import { connect } from 'react-redux'
import { get } from 'lodash'
import PropTypes from 'prop-types'
import toastr from 'toastr'
import { Route } from 'react-router-dom'
import { Redirect } from 'react-router'
import { LoadingIndicator } from 'components' export class PrivateRoute extends Component {
constructor (props) {
super(props) this.state = {
isLoading: true, // 是否於權限檢核中
isAuthed: false // 是否通過權限檢核
}
} static propTypes = {
component: PropTypes.any.isRequired,
funcCode: PropTypes.string.isRequired
} checkAuth = async () => {
let isAuthed = false
const { isLogin, funcCode } = this.props if (isLogin) { this.setState(state => ({ ...state, isLoading: true })) isAuthed = await api.checkAuthWithServer(funcCode)
} if (!isAuthed) { toastr.warning('系統未登录,请先登录')
} // 更新狀態 1.檢核結束 2.檢核結果
this.setState(state => ({ ...state, isAuthed: isAuthed, isLoading: false }))
} componentWillMount = async () => {
await this.checkAuth()
} componentWillReceiveProps = async (nextProps) => {
if (nextProps.location.pathname !== this.props.location.pathname) {
await this.checkAuth()
}
} render () {
const { component: Component, ...rest } = this.props
const { isLoading, isAuthed } = this.state return (
isLoading === true
? <LoadingIndicator />
: <Route {...rest} render={props => (
isAuthed
? <Component {...props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)} />
)
} } const mapStateToProps = state => ({
// 登入系統後會於 redux 中註記登入狀態
isLogin: get(state, 'auth.isLogin')
}) const mapDispatchToProps = dispatch => ({
}) export default connect(mapStateToProps, mapDispatchToProps)(PrivateRoute)

update privateRoute:

import React from 'react';
import {toastr} from "react-redux-toastr";
import {Route, withRouter} from 'react-router-dom';
import LoginUser from 'service/login-service/LoginUser'; import Unauthorized from "page/error/Unauthorized"; const _loginUser = new LoginUser();
//私有路由,只有登录的用户才能访问
class PrivateRoute extends React.Component{
constructor(props) {
super(props);
this.state = {
isAuth : _loginUser.hasLogin()
}
}
componentWillMount(){
if(!this.state.isAuth){
toastr.error('login timeOut, return to the login page after 3s');
const {history} = this.props;
setTimeout(() => {
history.replace("/login");
}, 3000)
}
}
render(){
const { component: Component, path="/", exact=false, strict=false} = this.props;
return this.state.isAuth ? (
<Route path={path} exact={exact} strict={strict}
render={(props)=>( <Component {...props} /> )} />) : <Unauthorized />;
}
}
export default withRouter(PrivateRoute);

react privateRoute的更多相关文章

  1. arcgis api 4.x for js 结合 react 入门开发系列react全家桶实现加载天地图(附源码下载)

    基于两篇react+arcgis的文章介绍,相信大家也能体会两者的开发区别了.在“初探篇”中作者也讲述了自己的选择,故废话不多说,本篇带大家体验在@arcgis/webpack-plugin环境下,使 ...

  2. react的路由权限控制

    在使用路由的时候,有的时候我们的界面只能够在登录之后才可以看的到,这个时候就需要使用路由权限控制了 找了资料发现一个就是我使用的方法,一个是高阶组件. 原谅菜鸟看不太懂不会使用高阶组件………… 首先在 ...

  3. react的登录逻辑

    https://blog.csdn.net/qq_36822018/article/details/83028661(先看看这个 https://blog.csdn.net/weixin_342681 ...

  4. react组件的生命周期

    写在前面: 阅读了多遍文章之后,自己总结了一个.一遍加强记忆,和日后回顾. 一.实例化(初始化) var Button = React.createClass({ getInitialState: f ...

  5. 十分钟介绍mobx与react

    原文地址:https://mobxjs.github.io/mobx/getting-started.html 写在前面:本人英语水平有限,主要是写给自己看的,若有哪位同学看到了有问题的地方,请为我指 ...

  6. RxJS + Redux + React = Amazing!(译一)

    今天,我将Youtube上的<RxJS + Redux + React = Amazing!>翻译(+机译)了下来,以供国内的同学学习,英文听力好的同学可以直接看原版视频: https:/ ...

  7. React 入门教程

    React 起源于Facebook内部项目,是一个用来构建用户界面的 javascript 库,相当于MVC架构中的V层框架,与市面上其他框架不同的是,React 把每一个组件当成了一个状态机,组件内 ...

  8. 通往全栈工程师的捷径 —— react

    腾讯Bugly特约作者: 左明 首先,我们来看看 React 在世界范围的热度趋势,下图是关键词“房价”和 “React” 在 Google Trends 上的搜索量对比,蓝色的是 React,红色的 ...

  9. 2017-1-5 天气雨 React 学习笔记

    官方example 中basic-click-counter <script type="text/babel"> var Counter = React.create ...

随机推荐

  1. go——变量

    在数学概念中,变量(variable)表示没有固定值且可以改变的数.但从计算机系统实现角度来看,变量是一段或多段用来存储数据的内存.作为静态类型语言,Go语言总是有固定的数据类型,类型决定了变量内存的 ...

  2. Django框架之单表操作

    一.添加表记录 对于单表有两种方式 # 添加数据的两种方式 # 方式一:实例化对象就是一条表记录 Frank_obj = models.Student(name ="海东",cou ...

  3. cdoj1344卿学姐种美丽的花

    地址:http://acm.uestc.edu.cn/#/problem/show/1344 题目: 卿学姐种美丽的花 Time Limit: 8000/4000MS (Java/Others)    ...

  4. 分组函数NTILE函数

    这个分组函数 并不是 group by的分组.

  5. 优秀 H5 案例收集 Vol.2(不定期更新)

    上期浏览:Vol.1 再见了,影史最性感的硬汉http://news.163.com/special/fdh5_wolverine/ 活出真我http://balfhcy.pernod-ricard- ...

  6. html5 canvas js(数字时钟)

      <!doctype html> <html> <head> <title>canvas dClock</title> </head ...

  7. 如何编写自己的虚拟DOM

    要构建自己的虚拟DOM,需要知道两件事.你甚至不需要深入 React 的源代码或者深入任何其他虚拟DOM实现的源代码,因为它们是如此庞大和复杂--但实际上,虚拟DOM的主要部分只需不到50行代码. 有 ...

  8. Boostnote:适合程序员的笔记软件【转】

    本文转载自:https://blog.csdn.net/u013553529/article/details/70306899 Boostnote:适合程序员的笔记软件 注意: Boostnote正在 ...

  9. Keras实现autoencoder

    Keras使我们搭建神经网络变得异常简单,之前我们使用了Sequential来搭建LSTM:keras实现LSTM. 我们要使用Keras的functional API搭建更加灵活的网络结构,比如说本 ...

  10. KMP(转自matrix67)

    蒟蒻笔者自己发现matrix67大佬讲的十分明白,然后现在网络上的排版也是有些微的问题,就稍稍改了一下,然后把代码改成了c++的. 如果机房马上要关门了,或者你急着要和MM约会,请直接跳到第六个自然段 ...