最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Redirection in React Router Dom v6 - Stack Overflow

programmeradmin2浏览0评论

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 redirect.

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

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 redirect.

<Route path="/login">
  <Route index element={<LoginStandard />} />
</Route>
Share Improve this question edited Apr 9, 2023 at 4:59 Youssouf Oumar 46.6k16 gold badges103 silver badges105 bronze badges asked Jun 17, 2022 at 13:16 n_d22n_d22 5231 gold badge8 silver badges21 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

Use the Navigate ponent to redirect. The conditional rendering logic still needs to be applied and ponents rendered out on the Route ponent'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 ponent that conditionally renders an Outlet for nested routes or the Navigate ponent.

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

With React Router Dom v6, you redirect with Navigate and useNavigate instead of Redirect and useHistory used in v5. Something like below. See the ments:

import { Navigate, useNavigate } from "react-router-dom";

export default function Foo() {
  const navigate = useNavigate();
  // Use navigate returned by useNavigate  when you are outside of JSX
  navigate("/");
  // Use Navigate the imported ponent when you are inside of JSX
  return <Route path="/login">{user ? <Navigate to="/" /> : <LoginStandard />}</Route>;
}
发布评论

评论列表(0)

  1. 暂无评论