如何在React Router中使用不同的参数链接到当前页面?

3
假设我设置了以下路由(仅为示例,实际路由不会这么凌乱):
<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>

从上面任何一个页面,我如何链接到同一个页面,但是使用不同的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


你的问题是如何从同一页面链接到同一页面,但传递不同的数据给自己? - linasmnew
这是一个被所有页面共享的组件,我想在该组件中呈现一个链接,以重定向到当前页面(使用不同的数据)。 - Vic
更新了我的问题。 - Vic
2个回答

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

本质上,我正在获取当前URL(location.pathname),并将当前用户ID(match.params.userid)替换为新的ID(bobId)。


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

嗯...我得每次使用SharedComponent时生成正确的路径并将其传递进去,这很烦人... - Vic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接