如何使用react-router的Redirect Component重定向到动态生成的路由?

时间:2016-05-19 15:48:55

标签: reactjs react-router redux

这是我的路线配置的简化版本。我正在使用react-router 2.4.0。现在,当我点击根'/'时,它会将我重定向到'父路线':

 <Redirect from="/" to="parent-route" />
 <Route path="/" component={App}>
     <Route path="parent-route" >
         <IndexRoute component={SomeComponent1} />
         <Route path="child-route-1/:entityId" component={SomeComponent2} />
         <Route path="child-route-2/:entityId" component={SomeComponent3} />       
    </Route>
</Route>

但是我想改变Redirect的行为以重定向到具有特定Id集的子路由。更确切地说,我想做这样的事情

<Redirect from="/" to="parent-route/child-route-1/[firstAvailableEntityId]" />

我有redux-store中所有可用实体的列表。有没有人知道如何将RedirectRedux-Store合并以生成动态重定向网址?

我尝试打包Redirect组件并将其连接到商店。但这不起作用,因为Redirect的render-method永远不会被调用。

1 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情:

import store from './yourStore.js'

function onIndexEnter (nextState, replace) {
    const state = store.getState()
    // put some logic here to decide your new id...
    replace(`/your-redirect-url/${newId}`
}

const routes = (<Redirect onEnter={onIndexEnter} from="/" to="parent-route" />
 <Route path="/" component={App}>
     <Route path="parent-route" >
         <IndexRoute component={SomeComponent1} />
         <Route path="child-route-1/:entityId" component={SomeComponent2} />
         <Route path="child-route-2/:entityId" component={SomeComponent3} />       
    </Route>
</Route>)

但我认为在这种情况下不使用Redirect会更容易和更清洁。相反,您可以将重定向逻辑放在顶级组件的componentWillMount内,或放在顶级路由的onEnter挂钩中,在那里您可以决定以动态方式重定向的位置。