我正在做一个项目,在管理路线时遇到了一些问题。我的前端分为两部分。一个用于客户端,另一个是用于处理客户端的管理面板。例如,如果我从管理面板添加一些博客,它就会显示在客户端。管理面板是为我的团队处理网站。假设用户将访问我的网站";www.mywebsite.com’,并且如果我输入";www.mywebsite.com/admin";则Admin面板和Admin组件应打开,而不是Nav组件。如何实现此条件路由?
这是App.js
import React, { Component, useEffect, useState } from "react";
import { Route, Switch } from "react-router-dom";
import Landing from "./components/Landing";
import Home from "./components/Home";
import About from "./components/About";
import Teams from "./components/Team";
import Events from "./components/Events";
import NotFound from "./components/NotFound";
import Blog from "./components/Blog";
import ContactUs from "./components/Contact";
import ComingSoon from "./components/ComingSoon";
import Navbar from "./components/Navbar";
import EventInfo from "./components/EventInfo";
import AdminNavbar from "./admin-panel/AdmiNavbar";
import Login from "./admin-panel/Login";
import Eventadd from "./admin-panel/Eventadd";
import Blogadd from "./admin-panel/Blogadd";
import Dashboard from "./admin-panel/Dashboard";
const NavComponents = () => {
return (
<>
<Switch>
<Route path="/home" exact component={Home} />
<Route path="/about" exact component={About} />
<Route path="/events" exact component={Events} />
<Route path="/team" exact component={Teams} />
<Route path="/blog" exact component={Blog} />
<Route path="/contact" exact component={ContactUs} />
<Route path="/comingsoon" exact component={ComingSoon} />
<Route path="/eventinfo/:eventName" exact component={EventInfo} />
<Route component={NotFound} />
</Switch>
</>
);
};
const AdminPanel = () =>{
return(
<>
<Switch>
<Route path="/admin/Eventadd" exact component={Eventadd}/>
<Route path="/admin/Blogadd" exact component={Blogadd}/>
<Route path="/admin/DashBoard" exact component={Dashboard}/>
<Route component={NotFound} />
</Switch>
</>
);
};
class App extends Component {
render() {
return (
<>
{window.location.pathname=="/"?"": <Navbar />}
<Switch>
<Route path="/" exact component={Landing} />
<NavComponents />
</Switch>
</>
);
}
}
export default App;
我假设如果用户通过"www.mywebsite.com/admin";链接,您想将它们重新路由到"/admin/DashBoard";路线管理面板不显示,因为它只返回具有EXACT匹配的路由。是可能的
A( 添加一个额外的路径来处理路由
<Route path=["/admin/DashBoard", "/admin"] exact component={Dashboard}/>
B( 如果您希望将路线保持为/admin/dashboard ,请添加管理员重定向
<Redirect exact from="/admin" to={`/admin/dashboard`} />
编辑:(最重要的(
此外,请注意,您没有将管理员包含在主路由器中。您不需要将管理员与导航分离。建议阅读文档https://reactrouter.com/web/api/Switch
Switch renders the first child <Route> or <Redirect> that matches the location.
总的来说,它应该像这个一样组合
<Switch>
...user paths
...admin paths
</Switch>