此问题在此处已有答案:
How to create a protected route with react-router-dom?(5个答案)
昨天关门了。
使用React Router Dom时,我遇到了一个问题。
假设我想进入一个配置文件页面,但用户必须先登录才能进入。因此,在本例中,我使用“导航”将用户重定向到“主页”,以防他们没有登录。但我的问题是,我想向用户显示一个警告,指定他必须先登录才能进入配置文件页面。
import React from "react";
import {
BrowserRouter as Router,
Link,
Route,
Routes,
Navigate,
} from "react-router-dom";
import NotFoundPage from "./pages/404/NotFoundPage";
import AboutPage from "./pages/about-faqs/AboutPage";
import HomePage from "./pages/home/HomePage";
import ProfilePage from "./pages/profile/ProfilePage";
import ProtectedRoute from "./pages/Protected-Routes/protectedRoute";
import TaskDetailPage from "./pages/tasks/TaskDetailPage";
import TasksPage from "./pages/tasks/TasksPage";
function AppRoutingOne() {
const logged = false;
return (
<Router>
<div>
<ul style={{ display: "flex", justifyContent: "space-between" }}>
<li>
<Link to="/"> Home </Link>
</li>
<li>
<Link to="/about"> About </Link>
</li>
<li>
<Link to="/faqs"> FAQs </Link>
</li>
</ul>
</div>
<main>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/faqs" element={<AboutPage />} />
//This is the part of my problem, in this case. How do I display an "alert()" inside the ternary operator?
<Route
path="/profile"
element={logged ? <ProfilePage /> : <Navigate to="/" replace /> }
/>
<Route path="/task" element={<TasksPage />} />
<Route path="/task/:id" element={<TaskDetailPage />} />
{/* 404 - Page Not Found */}
<Route path="*" element={<NotFoundPage />} />
</Routes>
</main>
</Router>
);
}
export default AppRoutingOne;
2条答案
按热度按时间zfciruhq1#
我编辑添加到您的代码,并添加新的组件:
在此组件中,您可以检查记录属性。如果记录为false,则可以向用户显示警报:
kkbh8khc2#
App.js
Outlet将是已经在子路由中的组件!