试图弄清楚嵌套路由为什么在我的子组件中不起作用。我在这里想念什么?下面是尝试同时使用路由“ /”和“ / add-new-strategy”时无法显示任何内容的组件。
这是我的组成部分。
import React from 'react'
import {
BrowserRouter as Router,
Switch,
Route
} from 'react-router-dom'
import { Nav } from '../../Nav'
import { Home } from '../Home'
import { Admin } from '../Admin'
import './index.scss'
export const App = () => {
return (
<Router>
<main className="main-container">
<Nav />
<Switch>
<Route path="/admin">
<Admin />
</Route>
<Route path="/" exact>
<Home />
</Route>
</Switch>
</main>
</Router>
)
}
这是子组件,即使我已完成并已完成,也不会显示任何内容。
import React from 'react'
import {
Switch,
Route
} from 'react-router-dom'
import { AdminSideBar } from '../../AdminSideBar'
import { AddNewStrategy } from '../AddNewStrategy'
export const Admin = () => {
return (
<div className="container-fluid">
<div className="row">
<AdminSideBar />
<div className="col-md-9 ml-sm-auto col-lg-10 px-md-4">
<Switch>
<Route path="/add-new-strategy">
<AddNewStrategy />
</Route>
<Route path="/" exact>
Dashboard should show up here...
</Route>
</Switch>
</div>
</div>
</div>
)
}
任何帮助将不胜感激。
答案 0 :(得分:0)
尝试:
import { BrowserRouter, Route, Switch } from 'react-router-dom'
<BrowserRouter>
<Switch>
<Route path="/add-new-strategy" component={AddNewStrategy} />
<Route path="/" exact component={Dashboard} />
</Switch>
</BrowserRouter>
答案 1 :(得分:0)
我发现使用useRouteMatch
指定有效的完整路径。
import React from 'react'
import {
Switch,
Route,
useRouteMatch
} from 'react-router-dom'
import { AdminSideBar } from '../../AdminSideBar'
import { AddNewStrategy } from '../AddNewStrategy'
export const Admin = () => {
const { path } = useRouteMatch()
return (
<div className="container-fluid">
<div className="row">
<AdminSideBar />
<div className="col-md-9 ml-sm-auto col-lg-10 px-md-4">
<Switch>
<Route path={`${path}/add-new-strategy`}>
<AddNewStrategy />
</Route>
<Route path={path} exact>
Dashboard should show up here...
</Route>
</Switch>
</div>
</div>
</div>
)
}
答案 2 :(得分:0)
从组件到下一个还有2种方法
<Route path="/add-new-strategy" component={AddNewStrategy} />
or
<Route path="/" exact render={()=>{<AddNewStrategy/>}} />
对于嵌套路由,请定义完整的网址并给出确切的“ true”
<Route path="/firstcomponent/secondcomponent" exact component={AddNewStrategy} />
请尝试这些