如何使用react-router从嵌套路由的根目录重定向?(How do I redirect from the root of a nested route with react-router?)

没有在网上找到任何答案,基本上我希望应用程序自动从我的路径根(/)重定向到'posts'。 所以www.app.com/user/1变成了www.app.com/user/1/posts

我尝试使用Redirect,但它实际上什么也没做。

<Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={HomePage}></IndexRoute> <Route path="user/:id" component={UserPage}> <Route path="tracks" component={UserPosts}></Route> <Redirect from="/" to="posts"/> </Route> </Route> </Router>

尝试将Redirect组件放在上面,它仍然无法正常工作。 有任何想法吗?

Didn't find any answers online to this, basically I want the application to automatically redirect from my route root (/) to 'posts'. So www.app.com/user/1 turns into www.app.com/user/1/posts

I tried using Redirect, but it actually does nothing.

<Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={HomePage}></IndexRoute> <Route path="user/:id" component={UserPage}> <Route path="tracks" component={UserPosts}></Route> <Redirect from="/" to="posts"/> </Route> </Route> </Router>

Tried putting the Redirect component above, and it still does not work. Any ideas?

最满意答案

我们在项目中使用的解决方案基于IndexRoute :

<IndexRoute onEnter={redirectToMainPage} />

其中redirectToMainPage定义为:

const redirectToMainPage = (nextState, replace, callback) => { replace(null, '/firstPage'); if (callback) { callback(); } };

这将允许动态选择重定向。

此外,您可以使用IndexRedirect :

<IndexRedirect to="/firstPage" />

我相信如果从/开始使用<Redirect>采用绝对路径from并且通常它对于空路径不太可靠。

The solution we are using in our project is based on IndexRoute:

<IndexRoute onEnter={redirectToMainPage} />

where the redirectToMainPage is defined as:

const redirectToMainPage = (nextState, replace, callback) => { replace(null, '/firstPage'); if (callback) { callback(); } };

This will enable to select the redirect dynamically.

Also, you can use IndexRedirect:

<IndexRedirect to="/firstPage" />

I believe that <Redirect> takes an absolute path if you start with / in from and in general it is less reliable for an empty path.

更多推荐

Redirect,component,user,电脑培训,计算机培训,IT培训"/> <meta name="descr