React-Router |我怎样才能一起使用IndexRoute和重定向?版本:1.0.0-rc1
问题描述:
如上所述,我怎样才能将它们一起使用?React-Router |我怎样才能一起使用IndexRoute和重定向?版本:1.0.0-rc1
像这样:
<Router history={history}>
<Route path="/" component={Root}>
<Route path='home' component={HomeContainer}></Route>
<Route path='about' component={AboutContainer}></Route>
<IndexRoute component={HomeContainer}/>
</Route>
</Router>
如果我需要的是服务于IndexRoute '/' 重定向到 '/家'?
我在react-router 1.0.0-rc1的文档中找不到任何线索。
谢谢。
[编辑]
只是为了阐述:
在上述结构中,当 '/' 被访问时,该网页将使用HomeContainer呈现;显示的内容与访问'/ home'时的内容完全相同。
所不同的是在浏览器地址栏中的网址:在前一种情况下的URL为“/”,在后一种情况下的URL为“/家”
我想的网址是相同的。所以我想要“/”(IndexRoute)直接重定向到“/ home”。
希望这可以说明我需要什么。
PS: 我可以用一个虚设部件,只有做了重定向,实现的行为:
<Router history={history}>
<Route path="/" component={Root}>
<Route path='home' component={HomeContainer}></Route>
<Route path='about' component={AboutContainer}></Route>
<IndexRoute component={DummyComponent}/> // which only does redirect
</Route>
</Router>
,并在DummyComponent:
componentDidMount() {
this.history.pushState(null, `/home`, null);
},
但似乎一点点的解决方法。
答
对我来说最好的解决方案是使用onEnter
函数。 (不知道这在2.0中如何工作,因为我在2.0上使用它)。
<IndexRoute onEnter={(targetState, replace) => {replace('/home')}} />
你能举一些例子吗?我发现很难理解你想要的行为。 – Clarkie
在问题中添加一些说明:) –