reactjs 在v6中React重定向?useNavigate()只能在组件的上下文中使用< Router>[重复]

unhi4e5o  于 2023-06-22  发布在  React
关注(0)|答案(1)|浏览(143)

此问题已在此处有答案

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
iqjalb3h

iqjalb3h1#

在路由器中使用上下文有什么原因吗?我觉得有点奇怪。

<Route
  path="page1"
  element={
    <PrivateRoute isLoggedIn={isLoggedIn}>
      <Page1 />
    </PrivateRoute>
  }
/>

这是PrivateRoute:

const PrivateRoute = ({ isLoggedIn, children }) => {
  if (!isLoggedIn) {
    return <Redirect path="/login"/>
  }
  return children
}

相关问题