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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
解決React報錯Rendered more hooks than during
這篇文章主要為大家介紹了React報錯Rendered more hooks than during the previous render解決方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12React?中使用?react-i18next?國際化的過程(react-i18next?的基本用法)
i18next?是一款強大的國際化框架,react-i18next?是基于?i18next?適用于?React?的框架,本文介紹了?react-i18next?的基本用法,如果更特殊的需求,文章開頭的官方地址可以找到答案2023-01-01react?express實現(xiàn)webssh?demo解析
這篇文章主要為大家介紹了詳解react?express實現(xiàn)webssh?demo解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04