简体   繁体   中英

Redirection In React-Router-Dom v6

What is the correct process for re-directions in v6? I was previously using the following code in v5, which was working fine:

<Route path="/login">
  {user ? <Redirect to="/" /> : <LoginStandard />}
</Route>

However, I would like to use the same logic in this version. When my user has logged in, I would like to re-direct.

<Route path="/login">
  <Route index element={<LoginStandard />} />
</Route>

With React Router Dom v6 you redirect with Navigate instead of Redirect . Something like so:

import {Navigate} from "react-router-dom";
<Route path="/login">
   { user ? <Navigate to="/" /> : <LoginStandard/>}
</Route>

Use the Navigate component to redirect. The conditional rendering logic still needs to be applied and components rendered out on the Route component's element prop.

Example:

<Route
  path="/login"
  element={user ? <Navigate to="/" replace /> : <LoginStandard />}
/>

It is often considered better practice to abstract this into a custom route protection component that conditionally renders an Outlet for nested routes or the Navigate component.

Example:

import { Navigate, Outlet } from 'react-router-dom';

const AnonymousRoute = ({ user }) => user
  ? <Navigate to="/" replace />
  : <Outlet />;

...

<Route element={<AnonymousRoute user={user} />}>
  <Route path="/login" element={<LoginStandard />} />
  ... other anonymous routes ...
</Route>
... other routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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