假设我设置了以下路线(只是一个例子,实际路线不是很乱):
<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>
从以上页面的 ANY ,如何链接到 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
答案 0 :(得分:2)
实际上,我找到了一种方法。不确定这是否是最好的方式,但它确实有效:
/**
* 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);
基本上,我正在使用当前网址(location.pathname
)并将当前用户ID(match.params.userid
)替换为新ID(bobId
)
答案 1 :(得分:0)
将带有路径道具的userId
传递给共享组件,如下所示
class Profile extends React.Component {
render() {
const bobId = 423423432; // Pass bobId with path from parent to child
return (
<SharedComponent path={"/stuff1/stuff2/`${bobId}`/profile"} />
);
}
}
class SharedComponent extends React.Component {
render() {
return (
<div>
<Link to={this.props.path}>
Redirect to the same page but with Bob's userid
</Link>
</div>
);
}
}
export default withRouter(SharedComponent);