没有登录直接访问页面跳转到登录页,官网的例子很详细了,参照官网做以下调整:
先把Route封装一下,判断一下用户是否登录,如果登录则正常router跳转,如果未登录则跳转登录页。代码:
privateRoute.jsx
import React, {Component} from 'react';
import {Route, withRouter} from 'react-router-dom';
class PrivateRoute extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: window.sessionStorage.getItem("userId") ? true: false
}
}
componentWillMount() {
if(!this.state.isAuthenticated){
const {history} = this.props;
setTimeout(() => {
history.replace("/login");
}, 1000)
}
}
render() {
let { component: Component, ...rest} = this.props;
return this.state.isAuthenticated ?
(<Route {...rest} render={(props) => ( <Component {...props} />
)}/> ) : (<p style = {{"width": "100%", "text-align": "center", "fontSize": "20px", "lineHeight": "50px"}}>请登录...</p>)
}
}
export default withRouter(PrivateRoute);
刚刚封装的路由引入页面
import PrivateRoute from "./privateRoute";
这样就可以了