如何使用反应路由器中的不同参数链接到当前页面?

时间:2017-12-08 16:40:21

标签: javascript reactjs react-router

假设我设置了以下路线(只是一个例子,实际路线不是很乱):

<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

2 个答案:

答案 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);