react privateRoute
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的更多相关文章
- arcgis api 4.x for js 结合 react 入门开发系列react全家桶实现加载天地图(附源码下载)
基于两篇react+arcgis的文章介绍,相信大家也能体会两者的开发区别了.在“初探篇”中作者也讲述了自己的选择,故废话不多说,本篇带大家体验在@arcgis/webpack-plugin环境下,使 ...
- react的路由权限控制
在使用路由的时候,有的时候我们的界面只能够在登录之后才可以看的到,这个时候就需要使用路由权限控制了 找了资料发现一个就是我使用的方法,一个是高阶组件. 原谅菜鸟看不太懂不会使用高阶组件………… 首先在 ...
- react的登录逻辑
https://blog.csdn.net/qq_36822018/article/details/83028661(先看看这个 https://blog.csdn.net/weixin_342681 ...
- react组件的生命周期
写在前面: 阅读了多遍文章之后,自己总结了一个.一遍加强记忆,和日后回顾. 一.实例化(初始化) var Button = React.createClass({ getInitialState: f ...
- 十分钟介绍mobx与react
原文地址:https://mobxjs.github.io/mobx/getting-started.html 写在前面:本人英语水平有限,主要是写给自己看的,若有哪位同学看到了有问题的地方,请为我指 ...
- RxJS + Redux + React = Amazing!(译一)
今天,我将Youtube上的<RxJS + Redux + React = Amazing!>翻译(+机译)了下来,以供国内的同学学习,英文听力好的同学可以直接看原版视频: https:/ ...
- React 入门教程
React 起源于Facebook内部项目,是一个用来构建用户界面的 javascript 库,相当于MVC架构中的V层框架,与市面上其他框架不同的是,React 把每一个组件当成了一个状态机,组件内 ...
- 通往全栈工程师的捷径 —— react
腾讯Bugly特约作者: 左明 首先,我们来看看 React 在世界范围的热度趋势,下图是关键词“房价”和 “React” 在 Google Trends 上的搜索量对比,蓝色的是 React,红色的 ...
- 2017-1-5 天气雨 React 学习笔记
官方example 中basic-click-counter <script type="text/babel"> var Counter = React.create ...
随机推荐
- ORACLE性能优化- Buffer cache 的调整与优化
Buffer Cache是SGA的重要组成部分,主要用于缓存数据块,其大小也直接影响系统的性能.当Buffer Cache过小的时候,将会造成更多的 free buffer waits事件. 下面将具 ...
- Android学习十二---在android上实现图像匹配
一.效果图及功能描述 效果图 点击ShowImg后 点击match,然后点击showmatch,可以不断点击showmatch. 主要功能描述:显示在SD卡上已经存在的图片test.jpg,根据图片在 ...
- Webbench进行网站压力测试
今天突然发现一个新大陆,Webbench,是linux下,用这很方便,开源,不限制并发访问次数和时间....大爱啊! 下载Webbench 使用wget 或者windows下载好导入linux也行, ...
- Django相关介绍
先认识一下MVC框架 MVC的框架模式,即模型M,视图V和控制器C.他们之间以一种插件似的,松耦合的方式连接在一起. Model(模型)是应用程序中用于处理应用程序数据逻辑的部分. 通常模型对象负责在 ...
- Python基础-面向对象1
class Bar: def fansik(self, name, age): print(name, age) obj = Bar() print(obj.fansik('fanjinbao', 1 ...
- beego——原生SQL查询
使用Raw SQL查询,无需使用ORM表定义. 多数据库,都可直接使用占位符号?,自动转换. 查询时的参数,支持使用Model Struct和Slice,Array ids := []int{1, 2 ...
- knit使用安装 ecstore knit位置 及调用路径
菜鸟一枚,接触php不久. 情况一: 最简单的: windows下, php文件引用kint 将kint放入c盘 php/pear下,我一般将kint包改名字为kint 结构如下: c:/php/pe ...
- 设置SVN提交日志必填
1.打开visualSVN Server2.打开Repositories3.右键需要控制的项目->所有任务->manage hooks...4.选择Hooks tab,点击Pre-comm ...
- python之路 RabbitMQ、SQLAlchemy
一.RabbitMQ RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统.他遵循Mozilla Public License开源协议. MQ全称为Message Queue, 消息队列 ...
- HDOJ 2203 亲和串 【KMP】
HDOJ 2203 亲和串 [KMP] Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...