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

首頁 > 語言 > JavaScript > 正文

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

2024-05-06 15:34:25
字體:
來源:轉載
供稿:網友

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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 宜章县| 江口县| 重庆市| 镇安县| 类乌齐县| 宜都市| 曲松县| 凤城市| 保康县| 苍梧县| 南康市| 新蔡县| 长寿区| 亳州市| 吕梁市| 永年县| 溆浦县| 固安县| 紫金县| 丹凤县| 扎赉特旗| 嘉义县| 建德市| 广安市| 延长县| 富顺县| 扬中市| 尤溪县| 敦化市| 柘荣县| 威海市| 延川县| 井冈山市| 沛县| 凤山市| 连云港市| 利津县| 竹山县| 确山县| 芦溪县| 邢台市|