一、创建PrivateRoute.js文件
import React, { Component } from 'react'
import { Route, Redirect } from 'react-router-dom'
function PrivateRoute({ children, ...rest }) {
// //从仓库取数据
// var t = Store.getState().chshz
// console.log(t, 'tttttt');
// console.log(localStorage.getItem('userLogin'), 'iiii');
return (
<Route
{...rest}
render={
({ location }) =>
localStorage.getItem('userLogin') ? (children) : (
<Redirect to={{
pathname: '/',
state: { from: location }
}} />
)
}
/>
)
}
export default PrivateRoute
二:路由设置拦截
import './App.css';
import { Route, Switch } from 'react-router-dom'
import Login from '../Login/Login'
import Home from '../Home/Home';
//路由守卫
import PrivateRoute from '../PrivateRoute'
function App() {
return (
<div className="App">
<Switch>
{/* 登录页首页 */}
<Route exact path='/' component={Login}></Route>
{/* 登录成功页面 */}
{/* <Route exact path='/home' component={Home}></Route> */}
<PrivateRoute path='/home'>
<Route path='/home' component={Home} >
</Route>
</PrivateRoute>
</Switch>
</div>
);
}
export default App;
?
三:登录页面
//登录按钮
async login() {
// console.log(this.state);
let msg = await getUser('User_Login', 'get', this.state)
console.log(msg);
if (msg.data.code == 200) {
localStorage.setItem('userLogin', this.state)
this.props.history.push('/home')
message.success('登录成功!');
} else {
message.warning('用户名/密码不正确')
}
}
|