React route v4中沒有vue的beforeEach的功能,可以用以下兩種思路,來做路由鑒權:
1. Route組件的render中鑒權
定義AuthRoute組件
import React from 'react' import PropTypes from 'prop-types' import { Route, Redirect } from 'react-router-dom' const AuthRoute = ({ component: Component, authenticated, redirectTo, ...rest}) => { return ( <Route {...rest} render={props => ( authenticated ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: redirectTo, state: { from: props.location } }} /> ) )} /> ) } AuthRoute.propTypes = { authenticated: PropTypes.bool, redirectTo: PropTypes.string.isRequired, component: PropTypes.func.isRequired, } AuthRoute.defaultProps = { authenticated: false, } export default AuthRoute
使用AuthRoute組件
import React, { Component } from 'react' import { AuthRoute } from 'react-router-auth' import UserProfile from './UserProfile' class Example extends Component { render () { return ( <AuthRoute path="/profile" component={UserProfile} redirectTo="/login" authenticated={this.props.authenticated} /> ) } }
類似實現的線上demo
2. history的listen方法中鑒權
// 加入對history的監聽 this.props.history.listen((location, action) => { // 執行內容, 第一個參數是當前的location, 第二個是此次執行的動作 console.log(action, location.pathname, location.state) })
要使用React router提供的history對象,可以從props中取到,不要使用自己定義的history對象,否則,監聽Link跳轉無效
參考:https://github.com/joelseq/react-router-auth
https://reactrouter.com/web/example/auth-workflow
https://www.zhihu.com/question/66731068