ホームページ  >  記事  >  ウェブフロントエンド  >  React-router ルートからの React のログイン検証制御手順の詳細な説明

React-router ルートからの React のログイン検証制御手順の詳細な説明

php中世界最好的语言
php中世界最好的语言オリジナル
2018-05-22 11:22:532875ブラウズ

今回は、react-routerroutingからのReactのログイン認証制御手順について詳しく説明します。 Reactがログイン認証制御を実行するために使用する注意事項は何ですか? . 一度見てみましょう。

検証コード

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>

この記事のケースを読んだ後は、この方法を習得したと思います。さらに興味深い情報については、PHP 中国語 Web サイトの他の関連記事に注目してください。

推奨書籍:

Reactルーティング管理React Routerの使用手順を詳しく解説

Vue.jsのダウンロード方法と使用手順を分析

以上がReact-router ルートからの React のログイン検証制御手順の詳細な説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。