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