我们常常遇到一种情况,有些页面是任何人后可以看见的,而有些页面是用户登陆后才可以看见的,这就需要我们对路由进行权限配置,下面的例子参考官网配置路由权限的例子。
对需要权限的路由的封装
import {
Route,
Redirect
} from 'react-router-dom';
import React, { Component } from 'react';
import { connect } from 'react-redux';
class PrivateRoute extends Component {
render() {
let { log, location, ...other } = this.props;
let component = log ?
<Route {...other} /> :
<Redirect
to={{
pathname: "/log"
}}
/>
return component;
}
}
const mapStateToProps = (state) => {
return state.log
}
export default connect(mapStateToProps, null)(PrivateRoute)
使用
<Switch>
<Route path='/' exact component={Home}/>
<Route path='/about' component={About}/>
<PrivateRoute path='/contact' component={Contact}/>
<PrivateRoute path='/products' component={Products}/>
<PrivateRoute path='/events' component={Events}/>
<Route path='/log' component={Log}/>
<Redirect from='/history' to='about/history'></Redirect>
<Route path='/details/:type' component={Details}></Route>
<Route component={NotFound404}/>
</Switch>
这样就实现了!!
网友评论