【发布时间】:2016-11-12 16:29:33
【问题描述】:
我正在尝试使用 react-router 构建布局系统。如果我正确理解文档,则使用 IndexRoute 等于将路由嵌套在彼此之下。
但是在下面的代码中,当我使用 IndexRoute 时,子路由没有被嵌套。但是如果
当我用正确的标签 <Route><sub-route/></Route> 嵌套它们时,它会按预期工作:
//THIS WORKS
export default function(history) {
return (
<Router history={history}>
<Route component={App}>
<Route path="/" component={Home}>
<IndexRedirect to="slides"/>
<Route path="slides" component={SlideShow}/>
<Route path="posts" component={Posts}/>
<Route path="questions" component={Questions} />
<Route path="questions/:id" component={Question} />
</Route>
</Route>
</Router>
)
}
//DOSEN'T GET NESTED
export default function(history) {
return (
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="slides" component={SlideShow}/>
<Route path="posts" component={Posts} />
<Route path="questions" component={Questions} />
<Route path="questions/:id" component={Question} />
</Route>
</Router>
)
}
为了说明这一点,如果我使用 IndexRoute 并从 home 组件中取出 this.props.children,子组件仍将被渲染。
这是 home 组件:
class Home extends Component{
render(){
//const {SlideShow, Posts} = this.props
return(
<div>
<h1>HOME PAGE!</h1>
<span><Link to="/slides">to slides</Link></span>
<span><Link to="/posts">to posts</Link></span>
<span><Link to="/questions">to question</Link></span>
<div>{this.props.children}</div>
</div>
)}
}
我的第二个问题是关于 IndexRedirect。如您所见,我使用它实质上将用户重定向到 /slides 路由。但我宁愿不使用重定向,而是使用 home 下的幻灯片 没有路径。像这样的:
<Router history={history}>
<Route component={App}>
<Route path="/" component={Home}>
<Route component={SlideShow}/>
<Route path="posts" component={Posts}/>
<Route path="questions" component={Questions} />
<Route path="questions/:id" component={Question} />
</Route>
</Route>
</Router>
这可能吗?
我正在努力实现以下目标: Using React-Router with a layout page or multiple components per page
只是我不太理解那里给出的示例,因为它不使用 IndexRoute 并且似乎遵循不同的模式。
【问题讨论】:
-
App 的 this.props.children 中默认为组件的IndexRoute,当你打开'/'时
-
对不起,我完全不明白你的评论
-
即home 组件会在 App 的 this.props.children 中,当你打开 '/'
-
我不明白你是说这是默认的吗?那么我该如何使用IndexRoute呢?
-
IndexRoute 用于此
标签: reactjs react-router