javascript - 如何在 react 路由器中链接到具有不同参数的当前页面?

标签 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>

如何从上面的任何页面链接到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/

相关文章:

javascript - 完整的 Javascript Ajax php 混淆

javascript - 移除 react.js 中的 DOM,

javascript - 如何编写一个返回 30 的函数 multiple(5)(6) ?

css - ReactCSSTransitionGroup 离开动画不适用于路由

javascript - 通过 onclick 事件从子级向父级 React js 发送数据?

javascript - 这是范围问题还是我设置的对象数组不正确?

javascript - 如何更新由EntityAdapter redux组成的嵌套对象?

reactjs - 在选择器中访问 react 路由器状态

javascript - 如何让 React-Router 呈现服务器的交互式输出?

javascript - <Route> 的 this.props.children 是否与其他 React 组件不同?