嵌套路由不起作用。 'Landing' 和 'home' 组件显示正确,但嵌套组件未呈现。
布局组件直接在app.js中导入 控制台中没有错误,但诸如“Feed”和“Myprofile”之类的嵌套组件未呈现。
查看代码
import React from 'react';
import { Route, Switch, BrowserRouter as Router} from 'react-router-dom';
import Sidebar from '../componants/Sidebar'
import Navbar from '../componants/Navbar';
import PathRouter from '../Routers/PathRouters'
import Landing from '../pages/Landing';
const Home=()=>{
return(
<>
<div className="container-fluid">
<Navbar />
<div className="rows row">
<div className='col-3'>
<Sidebar />
</div>
<div className="col-9 ">
<div className="content">
<Switch>
{PathRouter.map((prop, key) => {
return (
<Route
exact path={prop.path}
component={prop.component}
key={key}
/>
);
}
)}
</Switch>
</div>
</div>
</div>
</div>
</>
)
}
const Layout = () => {
return (
<>
<Router>
<Switch>
<Route exact path='/' component={Landing} />
<Route exact path='/home' component={Home} />
</Switch>
</Router>
</>
)
}
export default Layout;
这是 Pathrouter.js
import Feed from '../pages/Feed';
import Answer from '../pages/Answer';
import Addquestion from '../componants/Addquestion';
import Myprofile from '../componants/Myprofile';
var PathRouter = [
{
path: '/home/feed',
name: 'Feed',
component: Feed
},
{
path: '/home/answer/:q_id',
name: 'answer',
component: Answer
},
{
path: '/home/addquestion',
name: 'addquestion',
component: Addquestion
},
{
path: '/home/myprofile',
name: 'myprofile',
component: Myprofile
}
]
export default PathRouter;
答案 0 :(得分:0)
在 Layout
组件中,<Route exact path='/home' component={Home} />
行破坏了您的嵌套路由。对于要渲染的嵌套路由,父路由也必须渲染,因为 '/home/feed'
与 '/home'
不完全匹配,父路由将不会被渲染。从 exact
路由中删除 '/home'
。 – Jacob Smit