国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

React從react-router路由上做登陸驗證控制的方法

2019-11-19 13:52:43
字體:
來源:轉載
供稿:網友

本文介紹了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 <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}

路由上使用

<Router history={browserHistory}> <Route path="/admin" component={requireAuthentication(AdminComponent)} /></Router>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 横峰县| 遵化市| 乌审旗| 双柏县| 眉山市| 五华县| 烟台市| 灵台县| 双峰县| 清流县| 左云县| 茶陵县| 万源市| 祁连县| 静海县| 固阳县| 高密市| 井冈山市| 竹山县| 玉田县| 宁乡县| 庆云县| 西乌珠穆沁旗| 翁源县| 大名县| 监利县| 西宁市| 怀仁县| 高要市| 平果县| 镇巴县| 台南县| 望都县| 尼勒克县| 乌审旗| 长宁县| 蓝田县| 霍林郭勒市| 肃北| 泽州县| 姜堰市|