反应路由器重定向丢弃参数

时间:2017-04-13 18:54:18

标签: javascript reactjs routes react-router

我使用的是next版本的React 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>

这看起来像resolved issue,但它不起作用。我需要传递给to路线吗?

6 个答案:

答案 0 :(得分: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;

用法示例:

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

答案 1 :(得分:7)

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

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

答案 2 :(得分:2)

我这样做了,并且有效:

<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>

答案 3 :(得分:2)

您可以使用 generatePath

import { Switch, Route, Redirect, generatePath } from "react-router";

<Switch>
  <Route component={PageOne} path="/one" />
  <Route component={PageTwo} path="/two/:id" />
  <Route
    path="/three/:id"
    render={props => (
      <Redirect
        to={generatePath("/two/:id", {
          id: props.match.params.id,
        })}
      />
    )}
  />
  <Route component={NotFoundPage} path="*" />
</Switch>

答案 4 :(得分:1)

你可以这样做:

<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>

答案 5 :(得分:0)

此功能已添加到React Router 4 as of 4.3.0。如果您被锁定在4.3.x之前的版本中,那么Gleb的答案就是解决之道。