我正在尝试保护一个组件。在记录时,我将令牌的值存储在会话存储中。我正在尝试这个过程,如果存在任何令牌值,则可以访问受保护的页面,否则不能。
Routes.js 的代码:
import React from 'react';
import {Route,Routes,BrowserRouter as Router} from 'react-router-dom';
import { Navigate } from 'react-router-dom';
import Home from '../Components/Home/Home';
import About from '../Components/About/About';
import Header from '../Layout/Navigation/Header';
import {Reg} from '../Authentication/Registration/Reg';
import { Login } from '../Authentication/Login/Login';
const RootRoute = () => {
return (
<Router>
<Header/>
<Routes>
<Route path="" element={<Home />}></Route>
<Route path="about/*" element={window.sessionStorage.getItem('Token') ? <About />: <Navigate to="/login" ></Navigate>}></Route>
<Route path="reg" element={<Reg />}></Route>
<Route path="login" element={<Login />}></Route>
</Routes>
</Router>
)
}
export default RootRoute
Header.js 代码
import React from 'react';
import {Navbar,Nav,Container,NavDropdown} from 'react-bootstrap';
import {Link,useNavigate} from 'react-router-dom';
import './Header.css';
const Header = () => {
const navigate=useNavigate();
const logout=()=>{
window.sessionStorage.clear();
navigate('/login');
}
return (
<>
<Navbar bg="dark" variant="dark">
<Container>
<Navbar.Brand href="/">Document</Navbar.Brand>
<Nav className="me-auto">
<Nav.Link as={Link} to="/">Home</Nav.Link>
<Nav.Link as={Link} to="about">About us</Nav.Link>
<NavDropdown title="Sign In" id="basic-nav-dropdown">
<NavDropdown.Item as={Link} to="reg">Regration</NavDropdown.Item>
<NavDropdown.Item as={Link} to="login">Login</NavDropdown.Item>
</NavDropdown>
<button onClick={logout} className="logout">Log Out</button>
</Nav>
</Container>
</Navbar>
</>
)
}
export default Header
但是,每当我在导航栏中单击关于我们时,尽管存在令牌,它都会重定向到登录。请帮忙,怎么办?