[英]Default component in nested routes in React Router
In React Router I have a nested Route在 React Router 中,我有一个嵌套的 Route
<Route path='about' component={{main: About, header: Header}}>
<Route path='team' component={Team} />
</Route>
So now it shows Team when I go to /about/team
.所以现在当我去
/about/team
时它会显示 Team 。
But how do I set which Component to be seen when I visit /about
?但是,当我访问
/about
时,如何设置要查看的组件?
I have tried我努力了
<Route path='about' component={{main: About, header: Header}}>
<IndexRoute component={AboutIndex} />
<Route path='team' component={Team} />
</Route>
and和
<Route path='about' component={{main: About, header: Header}}>
<Route path='/' component={AboutIndex} />
<Route path='team' component={Team} />
</Route>
but it doesn't work.但它不起作用。
My About component looks like this我的 About 组件看起来像这样
class About extends React.Component {
render () {
return (
<div>
<div className='row'>
<div className='col-md-9'>
{this.props.children}
</div>
<div className='col-md-3'>
<ul className='nav nav-pills nav-stacked'>
<li className='nav-item'><IndexLink className='nav-link' to='/about' activeClassName='active'>About</IndexLink></li>
<li className='nav-item'><Link className='nav-link' to='/about/team'>Team</Link></li>
</ul>
</div>
</div>
</div>
);
}
}
The default route is the one without a path.默认路由是没有路径的路由。
import BrowserRouter from 'react-router-dom/BrowserRouter';
import Switch from 'react-router-dom/Switch';
import Route from 'react-router-dom/Route';
<BrowserRouter>
<Switch>
<Route exact path='/about' component={AboutIndex} />
<Route component={AboutIndex} /> // <--- don't add a path for a default route
</Switch>
</BrowserRouter>
If you don't need this object {main: About, header: Header}
in your component, then just put AboutIndex in the component attribute.如果您的组件中不需要此对象
{main: About, header: Header}
,则只需将 AboutIndex 放在组件属性中。 That should work那应该工作
<Router history={browserHistory}>
<Route path='about' component={AboutIndex}>
<IndexRoute component={AboutIndex} />
<Route path='team' component={Team} />
</Route>
</Router>
If you still need main and header components, just add them in as either parent, child, or sibling components depending on your needs如果您仍然需要主组件和标题组件,只需根据您的需要将它们添加为父组件、子组件或兄弟组件
The route has an attribute index
which is used to define the index route as per the docs .该路由有一个属性
index
,用于根据文档定义索引路由。
<Route index element={<DefaultPage />} />
Another way to do I found is to use the Navigate component of the react-router-dom package with the index
attribute.我发现的另一种方法是使用带有
index
属性的 react-router-dom 包的 Navigate 组件。 After the a user navigates to the support
route, it will default to the about
page in the following example.用户导航到
support
路线后,将默认为以下示例中的about
页面。
<Route path="support/*" element={<Support />}>
<Route index element={<Navigate to="about" replace />} />
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact/>} />
</Route>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.