React Router Redirect删除参数 [英] React Router Redirect drops param
本文介绍了React Router Redirect删除参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用React Router的 next
版本,它似乎正在删除params。我希望下面的重定向保留 channelId
的值,但到
路由使用文字字符串:channelId
而在路径中。
I am using the next
version of React Router, and it seems to be dropping params. I expect the redirect below to retain the value of channelId
, but the to
route uses the literal string ":channelId
" in the path instead.
<Switch>
<Route exact path="/" component={Landing} />
<Route path="/channels/:channelId/modes/:modeId" component={Window} />
<Redirect
from="/channels/:channelId"
to="/channels/:channelId/modes/window" />
</Switch>
这看起来像是已解决的问题,但它无效。我还需要传递给到
路线吗?
This looks like a resolved issue, but it's not working. Is there something else I need to pass to the to
route?
推荐答案
我在React Router 4中找不到这样的逻辑,所以写自己的解决方法:
I found no such logic in React Router 4 sources, so write own workaround:
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>
这篇关于React Router Redirect删除参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文