React從react-router路由上做登陸驗證控制的方法
更新時間:2018年05月10日 16:32:18 作者:戀月
本篇文章主要介紹了React從react-router路由上做登陸驗證控制的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本文介紹了React從react-router路由上做登陸驗證控制的方法,分享給大家,具體如下:
驗證代碼
import React from 'react'
import {connect} from 'react-redux';
function requireAuthentication(Component) {
// 組件有已登陸的模塊 直接返回 (防止從新渲染)
if (Component.AuthenticatedComponent) {
return Component.AuthenticatedComponent
}
// 創(chuàng)建驗證組件
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>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關文章
React使用高德地圖的實現(xiàn)示例(react-amap)
這篇文章主要介紹了React使用高德地圖的實現(xiàn)示例(react-amap),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04
Remix后臺開發(fā)之remix-antd-admin配置過程
這篇文章主要為大家介紹了Remix后臺開發(fā)之remix-antd-admin配置過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
react-native使用leanclound消息推送的方法
這篇文章主要介紹了react-native使用leanclound消息推送的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08

