简体   繁体   English

当用户单击注销按钮时,将用户从仪表板页面重定向到登录页面

[英]Redirect user from the dashboard page to login page when user click on logout button

Hi I have a user dashboard in which I'm showing some basic details of the users, and I have also given a logout button so onces user click on it he/she should be completely redirect to the login page, but the proble is when I'm trying to access the login page then by default the dashboard is also getting loaded.嗨,我有一个用户仪表板,其中显示了用户的一些基本详细信息,并且我还提供了一个注销按钮,因此一旦用户单击它,他/她应该完全重定向到登录页面,但问题是何时我正在尝试访问登录页面,然后默认情况下仪表板也会被加载。

I'm not sure where I have to add the login module into App.js我不确定必须在哪里将登录模块添加到 App.js

function App() {
return (
<Router>
<div className="App">
  <Topbar/>
  <div className='container'>
  <Sidebar/>
  <div className='others'>
  
  <Routes>
      <Route path="/" element={<Home/>} />
      <Route path="/createTrip" element={<CreateTrip/>} />
      <Route path="/allTrip" element={<AllTrip/>} />
      <Route path="/driverDetail" element={<DriverDetails/>} />
      <Route path="/myVehicle" element={<MyVehicle/>} />
  <Route path="*" element={<Home />} />
  </Routes>
  </div>
  </div>
  
  </div>
</Router>

); ); } }

在此处输入图像描述

As per my understanding of your question, You want to redirect to login page once you click on logout, but instead your dashboard is rendered.根据我对您问题的理解,您希望在单击注销后重定向到登录页面,而是呈现您的仪表板。

The approximation of your problem is redirection, private routing and session handling.您的问题的近似值是重定向、私有路由和 session 处理。

If you are handling user sessions (holding user login state in localStorage or in your app state), use private routes to check weather the user is logged in or not and accordingly redirect to the desired page.如果您正在处理用户会话(在 localStorage 或您的应用程序状态中持有用户登录 state),请使用私有路由来检查用户是否登录并相应地重定向到所需页面。

In your example it would be similar to adding nested routes with private route as their parent.在您的示例中,这类似于添加以私有路由为父级的嵌套路由。

Private Route -私人路线 -

import Navigate from "react-router-dom";
    export const PrivateRoute =({children}) => {
       if(localStorage.getItem("token")){
    return children
           } else {
                Navigate("/login")
           }
    
     }




        function App() {
    return (
    <Router>
    <div className="App">
      <Topbar/>
      <div className='container'>
      <Sidebar/>
      <div className='others'>
      
      <Routes>
          <Route path="/" element={<Home/>} />
          <Route path="/createTrip" element={<PrivateRoute><CreateTrip/></PrivateRoute>} />
          <Route path="/allTrip" element={<PrivateRoute><AllTrip/></PrivateRoute>} />
          // and so on
      </Routes>
      </div>
      </div>

      
      </div>

</Router>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM