假设我设置了以下路由(只是一个例子,实际路由并没有这么乱):
<Router>
<Switch>
<Route path="/app/fun/:userid/profile" component={Profile} exact/>
<Route path="/photos/:userid" component={Photos} exact/>
<Route path="/:userid/contact" component={Contact} exact/>
</Switch>
</Router>
如何从上面的任何页面链接到SAME页面,但使用不同的userid
?
例如:
/**
* Shared component that's rendered by Profile, Photos and Contact
*/
class SharedComponent extends React.Component {
render() {
const bobId = 423423432;
return (
<div>
<Link to={/* what to put here? */}>
Redirect to the same page but with Bob's userid
</Link>
</div>
);
}
}
export default withRouter(SharedComponent);
注意:使用 react router v4
最佳答案
实际上,我找到了一种方法来做到这一点。不确定这是否是最好的方法,但它有效:
/**
* Shared component that's rendered by Profile, Photos and Contact
*/
class SharedComponent extends React.Component {
render() {
const { location, match } = this.props;
const bobId = 423423432;
const bobUrl = location.pathname.replace(match.params.userid, bobId);
return (
<div>
<Link to={bobUrl}>
Redirect to the same page but with Bob's userid
</Link>
</div>
);
}
}
export default withRouter(SharedComponent);
本质上,我使用当前 url (location.pathname
) 并将当前用户 ID (match.params.userid
) 替换为新 ID ( >bobId
)
关于javascript - 如何在 react 路由器中链接到具有不同参数的当前页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47718597/