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. CKEditor的下载、配置与使用

    CKEditor简介: CKEditor 是一款功能强大的开源在线文本编辑器.它所见即所得的特点,使你在编辑时所看到的内容和格式,能够与发布后看到的效果完全一致.CKEditor 完全是基于 Java ...

  2. go——基本类型

    Go有许多预定义类型,这里简单把它们分为基本类型和高级类型.下面是基本类型列表: Go的基本类型共有18个,其中int和uint的实际宽度会根据计算架构的不同而不同.在386计算架构下,它的宽度为32 ...

  3. IE10、火狐浏、谷歌浏览器 KindEditor无法获取textarea值

    http://e-mailwu.blog.163.com/blog/static/651040362013311160913/ 在IE10.火狐浏览器.谷歌浏览器下后台KindEditor在线编辑器无 ...

  4. 144. Binary Tree Preorder Traversal (二叉树前序遍历)

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  5. Poj 2074 Line of Sight

    地址:http://poj.org/problem?id=2074 题目: Line of Sight Time Limit: 1000MS   Memory Limit: 30000K Total ...

  6. shell 学习一

    一.shell脚本 打开文本编辑器(可以使用vi/vim命令来创建文件),新建一个文件test.sh,扩展名为sh(sh代表shell),扩展名并不影响脚本执行 #!/bin/bash echo &q ...

  7. [转]从程序员到CTO的Java技术路线图

    原文链接:http://zz563143188.iteye.com/blog/1877266 在技术方面无论我们怎么学习,总感觉需要提升自已不知道自己处于什么水平了.但如果有清晰的指示图供参考还是非常 ...

  8. uvm的sequence

    1,每个sequence都有一个body任务.当一个sequence启动后,会自动执行sequence的body任务,所以在sequence的class中,一定要有一个名为body的task. 此外, ...

  9. [mongodb] MMAPv1 Storage Engine

    MMAPv1 是mongodb 在3.2以前默认的存储引擎,在3.2 之后默认的存储引擎为WiredTiger,MMAPv1存储引擎基于内存映射文件,它擅长高容量的插入,读取和更新. Journal ...

  10. Graph_Master(连通分量_B_Trajan+完全图)

    hdu_4635 题目大意:给出一张DAG(n个点,m条边),求出能加的最大边数,使得该图无重边,无自环,非强连通. 题解:这题题面很好理解,也没有什么很难的点,主要是如何求出最大边数需要动点脑筋.首 ...