如何在 React Router v4 中嵌套路由? [英] How to nest routes in React Router v4?
本文介绍了如何在 React Router v4 中嵌套路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 React Router v4 中嵌套路由?
这有效:
<主要><Route path='/' component={AppBar}/><Route path='/customers' component={Customers}/></main></路由器>
这不会:
<Route path='/' component={AppBar}><Route path='/customers' component={Customers}/></路线></路由器>
客户组件:
import React, { Component, PropTypes } from 'react'从样式组件"导入样式导出默认类客户扩展组件{使成为 () {返回 (<容器><h1>客户</h1></容器>)}}const Container = styled.section`高度:100%;填充:15px;溢出:自动;`
解决方案
迄今为止我发现的最佳模式.
//主应用<div>//不设置路径道具,使其始终呈现<路由组件={AppShell}/><开关><路由精确路径="/" component={Login}/><Route path="/dashboard" component={AsyncDashboard(userAgent)}/><路由组件={NoMatch}/></开关>
我可以继续将它嵌套在一个组件中,一切都很好,包括 hmr(如果使用 webpack,不要忘记将 output.publicPath
设置为 "/"
)
//仪表盘组件<div>//和之前一样,不设置路径属性//让它在每个/dashboard/** 请求上呈现<路由组件={DashboardTAB}/><开关>//首先比其他路径更长的路径(具有相同的根)<Route path="/dashboard/graphs/longerpath" component={GraphForm}/><Route path="/dashboard/graphs" component={Graphs}/><Route path="/dashboard/workers" component={List}/><Route path="/dashboard/insert" component={InsertComponent}/></开关>
Is there a way to nest routes in React Router v4?
This works:
<Router basename='/app'>
<main>
<Route path='/' component={AppBar} />
<Route path='/customers' component={Customers} />
</main>
</Router>
This does not:
<Router basename='/app'>
<Route path='/' component={AppBar}>
<Route path='/customers' component={Customers} />
</Route>
</Router>
Customers Component:
import React, { Component, PropTypes } from 'react'
import styled from 'styled-components'
export default class Customers extends Component {
render () {
return (
<Container>
<h1>Customers</h1>
</Container>
)
}
}
const Container = styled.section`
height: 100%;
padding: 15px;
overflow: auto;
`
解决方案
Best pattern I have found so far.
// main app
<div>
// not setting a path prop, makes this always render
<Route component={AppShell}/>
<Switch>
<Route exact path="/" component={Login}/>
<Route path="/dashboard" component={AsyncDashboard(userAgent)}/>
<Route component={NoMatch}/>
</Switch>
</div>
I can just keep nesting this inside a component and everything works nice including hmr(If using webpack, dont forget to set output.publicPath
to "/"
)
// dashboard component
<div>
// the same way as before, not setting a path prop
// makes it render on every /dashboard/** request
<Route component={DashboardTAB}/>
<Switch>
// longer path (with same root) than others first
<Route path="/dashboard/graphs/longerpath" component={GraphForm}/>
<Route path="/dashboard/graphs" component={Graphs}/>
<Route path="/dashboard/workers" component={List}/>
<Route path="/dashboard/insert" component={InsertComponent}/>
</Switch>
</div>
这篇关于如何在 React Router v4 中嵌套路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文