我有路由我传递id,但我不想在url中显示id,
`<Route path={`${match.url}invite-members/:groupID`} exact component={InviteMembers} />`
这会在网址https://local..../invite-members/5中转换,
但不是我想要的https://local..../invite-members,但功能应该保持相同,因为我在邀请成员中通过this.props.match.params.groupID
获取ID应该是原样,请帮助
使用反应路由器"react-router-dom": "^4.2.2",
答案 0 :(得分:1)
如果您想将网址更改为&#39; / invite-members&#39;,您可以添加重定向组件。如果您想保存groupId,可以将其保存到组件状态:
import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import {
Router,
Route,
Link,
Switch,
Redirect
} from "react-router-dom";
class Root extends PureComponent {
// add groupId field to your component
// In case you use redux or any another state management library, you can save groupId to store
state = { groupId: null };
render() {
const { store, history } = this.props;
// just for example I defined '/' path to redirect on /invite-members url
return (
<Router>
<Switch>
<Route
path="/"
exact
render={props => (
<Redirect
to={{
pathname: "/invite-members/123",
state: { from: props.location }
}}
/>
)}
/>
<Route
path="/invite-members"
exact
render={props => (
<InviteMembers {...props} groupId={this.state.groupId} />
)}
/>
<Route
path="/invite-members/:groupID"
exact
render={props => {
return (
<RedirectAndSaveGroupId
{...props}
groupId={props.match.params.groupID}
onSetGroupId={groupId => {
this.setState({ groupId });
}}
/>
);
}}
/>
</Switch>
</Router>
);
}
}
export default Root;
class RedirectAndSaveGroupId extends PureComponent {
componentDidMount() {
// save groupId to Root component
this.props.onSetGroupId(this.props.groupId);
}
render() {
// redirect to /invite-members without groupId
return (
<Redirect
to={{
pathname: "/invite-members",
state: { from: this.props.location }
}}
/>
);
}
}
// Just for demo. In this.props.groupId we can receive groupId
class InviteMembers extends PureComponent {
render() {
return this.props.groupId;
}
}
&#13;
请注意,如果您使用任何状态管理库(如Redux),您可以将组ID存储在其中
答案 1 :(得分:0)
在params
对象中传递数据将始终导致该数据显示在URL中。因为params
对象是从url构建的。
答案 2 :(得分:0)
我也许有一个非常简单的解决方案:
路由器链接:
<Link to={{pathname: '/item/'+name, state : {id}}}>{name}</Link>
在目标文件中:
state = this.props.location.state
QueryParameters = () => {
const id = this.state.id
return { id }
}
然后启动需要ID的查询。它不会显示在网址中。