在做dva.js项目时,涉及到登陆权限控制,在dva.js中提供了react-router的路由方法来控制路由,由于内置的是第四代react-router,我们还需要使用react-router-dom来更好地适应浏览器运行环境。
一般涉及到用户权限控制的应用都会在用户登陆后生成一个唯一标识,常见的就是token,我们可以在用户登陆成功后在浏览器本地存储或者cookie里面存储该标识,路由匹配时检测该标识后再进行正确匹配,退出则清除相应的数据。
- 核心代码,私有路由控制,作为一个公共组件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import React from 'react'; import { Route, Redirect, withRouter } from 'react-router-dom'; import PropTypes from 'prop-types';
class PrivateRoute extends React.Component{ componentWillMount(){ let isAuthenticated = localStorage.getItem('token') ? true : false; this.setState({ isAuthenticated }) if(!isAuthenticated){ const { history } = this.props; setTimeout(() => { history.replace('/Login') }, 1000) } } render(){ let { component: Component, path="/", exact=false, strict=false } = this.props; return this.state.isAuthenticated ? ( <Route path={path} exact={exact} strict={strict} render={(props) => ( <Component {...props} /> )} /> ) : ("请重新登录") } }
PrivateRoute.PropTypes = { path: PropTypes.string.isAuthenticated, exact: PropTypes.bool, strict: PropTypes.bool, component: PropTypes.func.isRequired }
export default withRouter(PrivateRoute);
|
- 私有路由使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import React from 'react'; import { Router, Route, Switch } from 'dva/router'; import App from './routes/App'; import Login from './routes/Login'; import Page from './routes/Page';
import PrivateRoute from './components/PrivateRoute';
function RouterConfig({ history }) { return ( <Router history={history}> <Switch> <Route path="/Login" component={Login} /> <PrivateRoute exact path="/" component={App} /> <PrivateRoute path="/page" component={Page} /> </Switch> </Router> ); }
export default RouterConfig;
|
- 登陆控制,这里只贴模拟登陆表单的简单代码,逻辑根据需求自行实现。
1 2 3 4 5 6 7 8 9
| handleSubmit = () => { let username = this.usernameInput.state.value let password = this.passwordInput.state.value if(username && password){ localStorage.setItem('token', username + password) alert('登录成功') setTimeout(()=>this.props.history.push('/'), 1500) } }
|
- 退出登录,清除相关标识。
1 2 3 4 5
| handleLoginOut = () => { alert('操作成功') localStorage.clear() setTimeout(()=>this.props.history.push('./Login') ,1500) }
|