此问题已在此处有答案:
Uncaught Error: useNavigate() may be used only in the context of a component. - What is it that I am doing wrong?(3个答案)
23小时前关闭
我想简单地重定向用户到'/login'谁是没有登录,并试图去一个路线,是专为登录用户。反之亦然,但重定向到'/'
我听说react-router-v6做事情的方式不同,甚至尝试使用chatGPT,他只是让我在一堆循环中处理不同的错误。
[navigate just refers to useNavigate() ]
let routes;
if (isLoggedIn) {
routes = (
<React.Fragment>
<Route exact path="/" element={<Searchbar changeHeader={setHeader} />} />
<Route path="/Result" element={<Result changeHeader={setHeader} topic={header} />} />
<Route path="/Chatbox/:sID" element={<Chatbox />} />
<Route path="/Assist" element={<Assist changeHeader={setHeader} />} />
navigate('/')
</React.Fragment>
);
} else {
routes = (
<React.Fragment>
<Route exact path="/" element={<Searchbar changeHeader={setHeader} />} />
<Route path="/Result" element={<Result changeHeader={setHeader} topic={header} />} />
<Route path="/Login" element={<LoginForm />} />
navigate('/login')
</React.Fragment>
);
}
this is the return component
return (
<AuthContext.Provider value={{ isLoggedIn: isLoggedIn, login: login, logout: logout }}>
<Router>
<div className="App">
{/* This is the main NAVBAR */}
<Navbar header={header} headersetter={setHeader} />
<div className="aSearch">
<Routes>
{routes}
</Routes>
</div>
</div>
</Router>
</AuthContext.Provider>
);
}
I tried using useHistory() but that wouldn't be possible cause not all routes have already been visited. Tried to use bunch of if conditions but made the code way messier
1条答案
按热度按时间iqjalb3h1#
在路由器中使用上下文有什么原因吗?我觉得有点奇怪。
这是PrivateRoute: