reactjs 如何从一个根路径重定向到另一个根路径并仍然呈现子路由?

cyvaqqii  于 2022-12-12  发布在  React
关注(0)|答案(2)|浏览(180)
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import Footer from './components/Footer';
import NavMenu from './components/NavMenu';
import ScrollToTop from './components/ScrollToTop';
import About from './pages/About';
import Contact from './pages/Contact';
import Home from './pages/Home';
import Projects from './pages/Projects';
import Gallery from './pages/Gallery';

export default function App() {
  return (
    <>
      <Router>
        <NavMenu />
        <ScrollToTop />
        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/contact">
            <Contact />
          </Route>
          <Route path="/projects">
            <Projects />
          </Route>
          <Route path="/gallery/">
            <Redirect to="/projects" />
            <Gallery />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
        <Footer />
      </Router>
    </>
  );
}

问题是,我希望它重定向(example.com/gallery)到(example.com/projects),但让我使用类似于(example.com/gallery/photo1)的内容,而不重定向到(example.com/projects)

jljoyd4f

jljoyd4f1#

呈现两个单独的路径,一个用于从"/gallery"重定向到"/projects",另一个用于 a 特定的画廊。
示例:

export default function App() {
  return (
    <>
      <Router>
        <NavMenu />
        <ScrollToTop />
        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/contact">
            <Contact />
          </Route>
          <Route path="/projects">
            <Projects />
          </Route>
          <Route path="/gallery/:galleryId">
            <Gallery />
          </Route>
          <Redirect from="/gallery" to="/projects" />
          <Route path="/">
            <Home />
          </Route>
        </Switch>
        <Footer />
      </Router>
    </>
  );
}
yvgpqqbh

yvgpqqbh2#

您可以使用exact属性指定精确路由,这意味着子路由将不匹配。

<Route exact path="/gallery/">
  <Redirect to="/projects" />
  <Gallery />
</Route>

相关问题