react privateRoute

Posted Nyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react privateRoute相关的知识,希望对你有一定的参考价值。

import React from ‘react‘;
import PropTypes from ‘prop-types‘;
import {Route,Redirect,withRouter} from ‘react-router-dom‘;
import LoginUser from ‘service/LoginUser‘;

//私有路由,只有登录的用户才能访问
class PrivateRoute extends React.Component{
    constructor(props) {
        super(props);
        this..state = {
            isAuth : _loginUser.hasLogin();
        }
    }
    componentWillMount(){
        if(!isAuth){
          const {history} = this.props;
          setTimeout(() => {
            history.replace("/login");
          }, 1000)
        }
    }
    render(){
        const { component: Component,path="/",exact=false,strict=false} = this.props;
        return this.state.isAuth ?  (
            <Route  path={path} exact={exact}  strict={strict}  render={(props)=>( <Component {...props} /> )} />
        ) : <Authenricated />;
    }
}
PrivateRoute.propTypes  ={
        path:PropTypes.string.isRequired,
        exact:PropTypes.bool,
        strict:PropTypes.bool,
        component:PropTypes.func.isRequired
}
export default withRouter(PrivateRoute);

 使用redux:

import { Component } from ‘react‘
import { connect } from ‘react-redux‘
import { get } from ‘lodash‘
import PropTypes from ‘prop-types‘
import toastr from ‘toastr‘
import { Route } from ‘react-router-dom‘
import { Redirect } from ‘react-router‘
import { LoadingIndicator } from ‘components‘


export class PrivateRoute extends Component {
  constructor (props) {
    super(props)

    this.state = {
      isLoading: true, // 是否於權限檢核中
      isAuthed: false  // 是否通過權限檢核
    }
  }

  static propTypes = {
    component: PropTypes.any.isRequired,
    funcCode: PropTypes.string.isRequired
  }

  checkAuth = async () => {
    let isAuthed = false
    const { isLogin, funcCode } = this.props

    if (isLogin) {
      
      this.setState(state => ({ ...state, isLoading: true }))

      isAuthed = await api.checkAuthWithServer(funcCode)
    }

    if (!isAuthed) {
     
      toastr.warning(‘系統未登录,请先登录‘)
    }

    // 更新狀態 1.檢核結束 2.檢核結果
    this.setState(state => ({ ...state, isAuthed: isAuthed, isLoading: false }))
  }

  componentWillMount = async () => {
    await this.checkAuth()
  }

  componentWillReceiveProps = async (nextProps) => {
    if (nextProps.location.pathname !== this.props.location.pathname) {
      await this.checkAuth()
    }
  }
  
  render () {
    const { component: Component, ...rest } = this.props
    const { isLoading, isAuthed } = this.state

    return (
      isLoading === true
        ? <LoadingIndicator />
        : <Route {...rest} render={props => (
            isAuthed
              ? <Component {...props} />
              : <Redirect to={{ pathname: ‘/login‘, state: { from: props.location } }} />
          )} />
    )
  }

}

const mapStateToProps = state => ({
  // 登入系統後會於 redux 中註記登入狀態
  isLogin: get(state, ‘auth.isLogin‘)
})

const mapDispatchToProps = dispatch => ({
})

export default connect(mapStateToProps, mapDispatchToProps)(PrivateRoute)

 

以上是关于react privateRoute的主要内容,如果未能解决你的问题,请参考以下文章

React Router 4.x - PrivateRoute 在连接到 Redux 后不起作用

PrivateRoute 在 reactjs react-router-dom 中不起作用

React Router - PrivateRoute,登录后重定向到原始目的地

在 Typescript 项目中实现 react-router PrivateRoute

错误:[PrivateRoute] 不是 <Route> 组件。 <Routes> 的所有子组件必须是 <Route> 或 <React.Fragment&g

react 中实现登录鉴权