react中怎么实现登录拦截
时间: 2024-06-12 17:10:47 浏览: 20
在 React 中实现登录拦截可以通过路由守卫来实现。具体步骤如下:
1. 安装 react-router-dom:`npm install react-router-dom`
2. 在 App.js 中引入 react-router-dom,并定义需要登录才能访问的路由:
```jsx
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
localStorage.getItem('isAuthenticated') === 'true'
? <Component {...props} />
: <Redirect to='/login' />
)} />
)
function App() {
return (
<Router>
<Switch>
<Route exact path="/login" component={Login} />
<PrivateRoute exact path="/" component={Home} />
<PrivateRoute exact path="/profile" component={Profile} />
</Switch>
</Router>
);
}
```
上面的代码中,PrivateRoute 是一个自定义组件,用于判断用户是否已经登录。如果已经登录,则渲染对应的组件;如果未登录,则重定向到登录页面。
3. 在登录成功后,将 isAuthenticated 存储到 localStorage 中:
```jsx
function handleLogin() {
// 登录成功后将 isAuthenticated 存储到 localStorage 中
localStorage.setItem('isAuthenticated', 'true');
// 跳转到首页
history.push('/');
}
```
4. 在退出登录时,将 isAuthenticated 从 localStorage 中删除:
```jsx
function handleLogout() {
// 退出登录时将 isAuthenticated 从 localStorage 中删除
localStorage.removeItem('isAuthenticated');
// 跳转到登录页面
history.push('/login');
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)