主要路线组成:
render() {
return (
<div className="container">
<Navbar/>
<Link to="/childComponent">Child</Link>
<Route path="/childComponent" component={ChildComponent}/>
<Navfooter/>
</div>
)
}
我想要路由到子组件的布局(主页)组件:
Ry4an Brase
由于不存在路线,我最终找不到页面。为什么会这样?我的路径路径不能进行路线注册,我可以轻松地通过链接标签进行导航......?
答案 0 :(得分:2)
只是为了解释为什么你最终会NotFound
。这是因为当您点击链接path
更改为/childComponent
时。道具改变,Routing
组件用新道具重新渲染。现在Switch
必须匹配新路径/childComponent
。他没有得到任何匹配并呈现默认组件NotFound
。
有两种方法可以解决这个问题:
更改路由路径:
export const Routing = () => (
<Switch>
<Route path='/layout' component={Layout}/>
<Route path='/stats' component={Statistic}/>
<Route path='/resource' component={Resource}/>
<Route component={Notfound} />
</Switch>
)
render() {
return (
<div className="container">
<Navbar/>
<Link to="/layout/childComponent">Child</Link>
<Route path="/layout/childComponent" component={ChildComponent}/>
<Navfooter/>
</div>)
}
另一种方法是重用组件:
export const Routing = () => (
<Switch>
<Route exact path='/' component={Layout}/>
<Route path="/childComponent" component={ChildComponent}/>
<Route path='/stats' component={Statistic}/>
<Route path='/resource' component={Resource}/>
<Route component={Notfound} />
</Switch>
)
const AppContainer = ({ children }) => (
<div className="container">
<Navbar/>
{children}
<Navfooter/>
</div>
)
/** Layout **/
render() {
return (
<AppContainer>
<Link to="/childComponent">Child</Link>
</AppContainer>
)
}
const ChildComponent = () => (
<AppContainer/>
....
<AppContainer/>
)