国产探花免费观看_亚洲丰满少妇自慰呻吟_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>

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

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

圖片精選

主站蜘蛛池模板: 湛江市| 张家港市| 信阳市| 手机| 彭州市| 宜兴市| 永登县| 和政县| 灵川县| 鄂温| 荣成市| 尚义县| 新余市| 武汉市| 罗甸县| 金堂县| 湛江市| 塔城市| 双鸭山市| 漳平市| 河间市| 陵川县| 洛浦县| 瓮安县| 容城县| 清原| 抚远县| 十堰市| 将乐县| 万宁市| 纳雍县| 平定县| 茂名市| 莱芜市| 苏尼特右旗| 兴安县| 饶河县| 都兰县| 镇江市| 陇南市| 高青县|