如何在React v4中实现子路由?附主路由与布局组件代码
实现React Router v4的子路由功能
没问题,我帮你一步步搞定这个子路由的实现,其实React Router v4的子路由逻辑很直观,就是在父组件里直接嵌套Route组件就行,结合你的代码具体来说:
第一步:调整主路由的配置
你原来的主路由里,Layout的Route加了exact属性,这会导致当访问/childComponent时,因为路径不是严格的/,Switch会直接跳过Layout去匹配后面的路由,最后落到Notfound上,这肯定不是你想要的。所以首先要修改主路由:
export const Routing = () => ( <Switch> {/* 先放更具体的顶级路由,确保访问/stats、/resource时直接渲染对应组件 */} <Route path='/stats' component={Statistic}/> <Route path='/resource' component={Resource}/> {/* 去掉exact,让所有以/开头的未匹配路径都进入Layout */} <Route path='/' component={Layout}/> {/* 这里不需要单独的Notfound了,后续可以在Layout里处理子路由的404 */} </Switch> )
第二步:在Layout组件中添加子路由
接下来修改你的Layout组件,React Router会自动给路由组件传递match、location、history这三个props,我们可以用match.path来灵活构建子路由的路径(这样以后如果Layout的父路径变了,子路由也能自动适配):
// 别忘了导入需要的路由组件 import { Route, Switch, Link } from 'react-router-dom'; class Layout extends Component { render() { // 从props中解构出match对象 const { match } = this.props; return ( <div className="container"> <Navbar/> {/* 用match.path构建子路由的跳转链接,比写死/childComponent更灵活 */} <Link to={`${match.path}childComponent`}>Child</Link> {/* 这里是子路由的渲染区域,用Switch包裹确保只渲染第一个匹配的子路由 */} <Switch> {/* 当路径是/(也就是Layout的默认路径)时,渲染首页内容组件 */} <Route exact path={match.path} component={HomeContent} /> {/* 匹配/childComponent路径,渲染你的子组件 */} <Route path={`${match.path}childComponent`} component={ChildComponent} /> {/* 如果访问的是/xxx这类未定义的子路径,渲染Layout内部的404组件 */} <Route component={LayoutNotFound} /> </Switch> </div> ); } }
几个关键注意点
- 一定要确保你的整个路由体系被
BrowserRouter(或HashRouter)包裹,比如在根组件里:
import { BrowserRouter } from 'react-router-dom'; ReactDOM.render( <BrowserRouter> <Routing /> </BrowserRouter>, document.getElementById('root') );
- 子路由的路径可以用绝对路径(比如
/childComponent),但用match.path拼接的相对路径更灵活,适合未来路径调整的场景。 - 如果需要在Layout外处理顶级404(比如访问完全不存在的路径,且不属于Layout的子路由),可以在主路由的最后添加
Route component={Notfound},但要注意放在Layout的Route后面,不过一般建议把404放在对应的路由层级里,用户体验更好。
内容的提问来源于stack exchange,提问作者EugenSunic
相关产品推荐
相关产品推荐

