gpt4 book ai didi

javascript - React router最新版本中,如何在首页嵌套路由 "/"

转载 作者:行者123 更新时间:2023-12-03 00:33:07 25 4
gpt4 key购买 nike

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

假设您有一个 2 页网站,主页只有标题和段落,“关于”页面还有 2 个嵌套路由,这是“关于”页面。

关于

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

索引

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 为“/”的主页有 2 个嵌套路由怎么办?我尝试切换他们的内容,但不起作用

最佳答案

如果主页必须有嵌套路由,您要做的就是从其路径中删除确切的关键字,并在 Switch 组件中重新排序路由

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

关于javascript - React router最新版本中,如何在首页嵌套路由 "/",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53775115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com