在React Router的最新版本中,如何在首页“ /”中嵌套路由

时间:2018-12-14 07:20:35

标签: javascript reactjs react-router-dom web-frontend

如何在首页“ /”中嵌套路线?

假设您有一个2页的网站,HOME页仅包含标题和段落,而ABOUT页则有2条嵌套的路线,这是About页。

关于

import React from "react";
import { Link, Route, Switch, Redirect } from "react-router-dom";
/* Inner Pages */
import Technology from "./innerpages/Technology";
import Business from "./innerpages/Business";


const About = props => {
  return (
    <div className="container">
        <div className="tab-navs">
            <Link to={`${props.match.url}/business`}>Business</Link>
            <Link to={`${props.match.url}/economics`}>Economics</Link>
        </div>
          <Switch>
            <Route
              exact
              path={`${props.match.path}/business`}
              render={() => <Business />}
            />
            <Route
              path={`${props.match.path}/economics`}
              render={() => <Economics />}
            />
          </Switch>
    </div>
  );
};

export default About;

首页

import React from "react";

const Home = props => {
  return (
    <div className="container">
        <h1>Home</h1>
        <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p>
    </div>
  );
};

export default Home;

这是index.js

INDEX

import React,{Component} from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Logo from "./components/Logo";
import Navigation from "./components/Navigation";

/* Pages */
import Home from "./pages/Home";
import About from "./pages/About";

import "./stylesheet/main.scss";

class App extends Component {
  constructor(props){
     super(props);
  }
 render(){
  return (
    <Router>
      <div className="App">
        <header>
          <Logo />
          <Navigation />
        </header>
        <main>
          <Switch>
            <Route path="/" exact render={props => <Home />} />
            <Route path="/about" component={About} />
          </Switch>
        </main>
      </div>
    </Router>
  );
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

现在这可以正常工作,但是如果URL为“ /”的HOMEPAGE具有2个嵌套路由,该怎么办?我试图切换他们的内容,但不起作用

1 个答案:

答案 0 :(得分:1)

如果首页必须具有嵌套的路由,您要做的是从其路径中删除确切的关键字,然后在Switch组件中重新排列您的路由

  <Switch>
        <Route path="/about" component={About} />
        <Route path="/services" component={Services} />
        <Route path="/" render={props => <Home {...props}/>} />
  </Switch>