我使用的是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路由?
发布于 2017-09-06 08:16:21
这是我一直在使用的答案,类似于其他答案,但没有依赖关系:
<Route
exact
path="/:id"
render={props => (
<Redirect to={`foo/${props.match.params.id}/bar`} />;
)}
/>发布于 2017-06-12 22:51:25
我在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>发布于 2017-10-26 00:02:38
您可以这样做:
<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>https://stackoverflow.com/questions/43399740
复制相似问题