React Router Redirect删除参数

Mat*_*ris 12 javascript routes reactjs react-router

我正在使用nextReact Router 的版本,它似乎正在删除params.我希望下面的重定向保留值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>
Run Code Online (Sandbox Code Playgroud)

这看起来像一个已解决的问题,但它不起作用.我需要传递给to路线的其他东西吗?

小智 7

我在React Router 4中找不到这样的逻辑,所以写自己的解决方法:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import pathToRegexp from 'path-to-regexp';
import { Route, Redirect } from 'react-router-dom';

class RedirectWithParams extends Component {
  render() {
    const { exact, from } = this.props;    
    return (
      <Route
        exact={exact}
        path={from}
        component={this.getRedirectComponent}
      />);
  }

  getRedirectComponent = ({ match: { params } }) => {
    const { push, to } = this.props;
    const pathTo = pathToRegexp.compile(to);
    return <Redirect to={pathTo(params)} push={push} />
  }
};

RedirectWithParams.propTypes = {
  exact: PropTypes.bool,
  from: PropTypes.string,
  to: PropTypes.string.isRequired,
  push: PropTypes.bool
};

export default RedirectWithParams;
Run Code Online (Sandbox Code Playgroud)

用法示例:

<Switch>
   <RedirectWithParams
      exact from={'/resuorce/:id/section'}
      to={'/otherResuorce/:id/section'}
   />
</Switch>
Run Code Online (Sandbox Code Playgroud)


Jas*_*n D 7

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

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


Fáb*_*tos 5

你可以这样做:

<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>
Run Code Online (Sandbox Code Playgroud)


Emm*_*kwe 5

我这样做了,它奏效了:

<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>
Run Code Online (Sandbox Code Playgroud)