新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

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

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

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名网站空间、营销软件、网站建设、盘山网站维护、网站推广。

验证代码

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 
   }
   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
}

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


文章名称:React从react-router路由上做登陆验证控制的方法-创新互联
标题路径:http://www.wjwzjz.com/article/ddipeo.html
在线咨询
服务热线
服务热线:028-86922220
TOP