2017-04-13 42 views
7

我使用的是React Router的next版本,它似乎在丢弃参数。我期望下面的重定向保留channelId的值,但to路径改为在路径中使用文字字符串“:channelId”。反应路由器重定向丢弃参数

<Switch> 
    <Route exact path="/" component={Landing} /> 
    <Route path="/channels/:channelId/modes/:modeId" component={Window} /> 
    <Redirect 
    from="/channels/:channelId" 
    to="/channels/:channelId/modes/window" /> 
</Switch> 

这看起来像一个resolved issue,但它不工作。还有什么我需要传递给to路线?

+0

你找到解决办法,马特? –

+0

@SebastianRoth不幸的是,我从来没有这样做过。我现在以不同的方式做事,在组件本身中使用重定向。然而,这将是很好的得到这个验证,因为它应该像在上面链接的线程中宣传的那样工作。 –

+1

FWIW,我在反应路由器Discord频道问过这个问题。我最终做了一些类似的事情,用一个渲染方法返回一个重定向,其中的值来自道具。 –

回答

4

我没有找到这样的逻辑做出反应路由器4种源,所以写自己的解决方法:

import pathToRegexp from 'path-to-regexp'; 
import { Route, Switch, Redirect } from 'react-router-dom'; 

const RedirectWithParams = ({ exact, from, push, to }) => { 
    const pathTo = pathToRegexp.compile(to); 
    return (
    <Route exact={exact} path={from} component={({ match: { params } }) => (
     <Redirect to={pathTo(params)} push={push} /> 
    )} /> 
    ); 
}; 

使用示例:

<Switch> 
    <RedirectWithParams 
     exact from={'/resuorce/:id/section'} 
     to={'/otherResuorce/:id/section'} 
    /> 
</Switch> 
+0

看起来几乎与你的代码相同:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/generatePath.js – coblr

+0

非常感谢,这正是我一直在寻找 – Anil

2

这是我一直在使用的东西,类似于其他答案但没有依赖性:

<Route 
    exact 
    path="/:id" 
    render={props => (
    <Redirect to={`foo/${props.match.params.id}/bar`} />; 
)} 
/> 
0

你可以这样做:

<Switch> 
    <Route exact path="/" component={Landing} /> 
    <Route path="/channels/:channelId/modes/:modeId" component={Window} /> 
    <Route 
    exact 
    path="/channels/:channelId" 
    render={({ match }) => (
     <Redirect to={`/channels/${match.params.channelId}/modes/window`} /> 
    )} 
    /> 
</Switch> 
0

我这样做,和它的工作:

<switch> 
 
    <Route path={`/anypath/:id`} component={Anycomponent} /> 
 
    <Route 
 
     exact 
 
     path="/requestedpath/:id" 
 
     render={({ match }) => { 
 
     if (!Auth.loggedIn()) { 
 
      return <Redirect to={`/signin`} />; 
 
     } else { 
 
      return <Redirect to={`/anypath/${match.params.id}`} />; 
 
     } 
 
     }} 
 
    /> 
 
</switch>