React从react-router路由上做登陆验证控制的方法

本文介绍了React从react-router路由上做登陆验证控制的方法分享给大家,具体如下:

验证代码

rush:js;"> import React from 'react' import {connect} from 'react-redux';

function requireAuthentication(Component) {
// 组件有已登陆的模块 直接返回 (防止从新渲染)
if (Component.AuthenticatedComponent) {
return Component.AuthenticatedComponent
}

// 创建验证组件
class AuthenticatedComponent extends React.Component {
static contextTypes = {
router: React.PropTypes.object.isrequired,}

state = {
login: true,}

componentwillMount() {
this.checkAuth();
}

componentwillReceiveProps(nextProps) {
this.checkAuth();
}

checkAuth() {

// 判断登陆
const token = this.props.token;
const login = token ? token.login : null;

// 未登陆重定向到登陆页面
if (!login) {
let redirect = this.props.location.pathname + this.props.location.search;
this.context.router.push('/login?message=401&redirect_uri=' + encodeURIComponent(redirect));
return;
}

this.setState({login});
}

render() {
if (this.state.login) {
return <Component {...this.props}/>
}
return ''
}
}

// 不使用 react-redux 的话直接返回
// Component.AuthenticatedComponent = AuthenticatedComponent
// return Component.AuthenticatedComponent

function mapStatetoProps(state) {
return {
token: state.token,};
}

function mapdispatchToProps(dispatch) {
return {};
}
Component.AuthenticatedComponent = connect(mapStatetoProps,mapdispatchToProps)(AuthenticatedComponent);
return Component.AuthenticatedComponent
}

路由上使用

rush:js;">

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...