【问题标题】:How to use react-router's Redirect Component to redirect to a dynamically generated route?如何使用 react-router 的重定向组件重定向到动态生成的路由?
【发布时间】:2016-09-16 15:08:39
【问题描述】:

这是我的路线配置的简化版本。我正在使用反应路由器 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 的渲染方法永远不会被调用。

【问题讨论】:

    标签: reactjs react-router redux


    【解决方案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>)
    

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

    【讨论】:

    • 感谢您的回答。我想我会在这里尝试一种没有重定向的方法。
    猜你喜欢
    • 1970-01-01
    • 2021-07-24
    • 2016-04-16
    • 1970-01-01
    • 2022-12-30
    • 2015-09-30
    • 2018-08-31
    • 2015-12-24
    • 2020-10-08
    相关资源
    最近更新 更多