我正在创建基本的反应应用程序,但在设置导航时遇到问题。下面是导航栏组件的代码,一旦用户单击注销按钮,该组件应清除身份验证上下文并将用户带到应用程序的根页面。但是,当我单击按钮时,它会进入处理程序,清除身份验证上下文,但随后保留在同一页面/url 上。以下是在我的应用程序中创建导航栏和路线的方式:
`const Navbar = () => {
const { setAuth } = useContext(AuthContext)
const navigate = useNavigate();
const handleLogout = (e) => {
setAuth(null)
navigate("/");
console.log("logout has been clicked");
}
return (
<nav>
<input type="checkbox" id="check"/>
<label for="check" className="checkbtn">
<i className="fas fa-bars">Quz</i>
</label>
<label className="logo">Create Your Best Team</label>
<ul>
<li><Link to="">Messages</Link></li>
<li><Link to="/student" className="active">Profile</Link></li>
<li><Link to="">My Group</Link></li>
<li><Link onClick={handleLogout}>Logout</Link></li>
</ul>
</nav>
)
}
export default Navbar;`
`import Login from './components/Login'
import Student from './components/Student';
import Teacher from './components/Teacher'
import Navbar from './components/Navbar/Navbar';
import { MantineProvider } from '@mantine/core';
import { Routes, Route } from 'react-router-dom';
import { useContext } from "react"
import RequireAuth from './customHooks/RequireAuth';
import AuthContext from "./context/AuthProvider";
function InnerApp() {
const { auth } = useContext(AuthContext)
return (
<MantineProvider>
{auth?.name ? <Navbar /> : <div></div>}
<Routes>
<Route exact path='/' element={<Login />} />
<Route exact element={<RequireAuth authID={{id: 1}}/>}>
<Route exact path='/teacher' element={<Teacher />}/>
</Route>
<Route exact element={<RequireAuth authID={{id: 2}}/>}>
<Route exact path='/student' element={<Student />}/>
</Route>
</Routes>
</MantineProvider>
);
}
export default InnerApp;`
`const RequireAuth = (props) => {
const {auth} = useContext(AuthContext);
// console.log(props.authID.id);
// console.log(auth?.id);
return (
auth?.id === props.authID?.id ? <Outlet /> : <div>404 Cannot go to his link</div>
)
}
export default RequireAuth`
我注意到实际的导航命令通过尝试导航(-1)来工作,这将我带到上一页。但是,由于我将开始添加更多页面,因此转到上一页是不够的,我想将客户端重定向到主页。我假设我设置的路线有问题。谢谢您的帮助。
看起来缺少
BrowserRouter
提供商。确保 useNavigate
钩子用在 BrowserRouter
内部
主应用程序应该看起来像,
const App = () => {
return (
<BrowserRouter>
<InnerApp />
</BrowserRouter>
);
}