App.tsx
import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from "react-router-dom";
import Dashboard from "./components/dashboard";
import "./App.css";
class App extends React.Component {
public render() {
return (
<Router>
<Switch>
<Route path="/dashboard" component={Dashboard} />
<Redirect path="/" to="/dashboard/home" />
</Switch>
</Router>
);
}
}
export default App;
Dashboard.tsx
import React from "react";
import { Switch, Route } from "react-router-dom";
import MainDashboard from "./MainDashboard";
class Dashboard extends React.Component {
public render() {
return (
<div>
<div>Dashboard</div>
<Switch>
<Route path="/dashboard/home" Component={MainDashboard} />
</Switch>
</div>
);
}
}
export default Dashboard;
MainDashboard.tsx
import React from "react";
class MainDashboard extends React.Component {
public render() {
return (
<div>
MainDashboard
</div>
);
}
}
export default MainDashboard;
有r条嵌套路线。第一个是App.tsx中的父路由,然后嵌套的路由是Dashboard.tsx中的路由。 预期的结果是使用/ dashboard / home将渲染MainDashboard组件。但这不起作用。
答案 0 :(得分:0)
要创建嵌套的路由,我们需要使用match.url
并添加一些我们想要渲染的检查,react-router-dom
将把match
对象注入为this.props
。
我们使用exact path={match.url}
作为我们的“基本路线”,并将子路线添加为path={`${match.url}/:sectionNAme`}
class App extends React.Component {
public render() {
return (
<Router>
<Switch>
<Route path="/dashboard" component={Dashboard} />
<Route path="/" render={() => <Redirect to="/dashboard/home" />} />
</Switch>
</Router>
);
}
}
class Dashboard extends React.Component {
public render() {
const { match } = this.props;
return (
<div>
<Route exact path={match.url} render={() => <div>Dashboard</div>} />
<Route path={`${match.url}/home`} component={MainDashboard} />
</div>
);
}
}
class MainDashboard extends React.Component {
public render() {
return (
<div>
MainDashboard
</div>
);
}
}