将参数从链接传递到组件 - react-router-dom

Passing params from links to components - react-router-dom

我正在尝试构建个人资料页面,在其中显示用户信息。

路由是 - localhost:3000/profile/,我想防止在 url.

中显示用户 ID

示例:我只想查看 localhost:3000/profile/.localhost:3000/profile/10 而不是 localhost:3000/profile/10

我现在用的是第一种方式,老板让我换成第二种方式。

不过,获取当前登录用户的 ID 非常容易。我的挑战是至少将列出的用户的 ID 传递给配置文件组件。

我正在使用 react-router-dom 和 redux。感谢帮助

考虑到您可以从 url 中删除用户 ID,我将告诉您如何通过 link 传递 ID。由于您使用的是 react-router-dom,您只需将用户 ID 传递为:

<Link to={{
  pathname: '/profile',
  state: { id: userId }
}}>
  <button>Profile</button>
</Link> 

此处对于 userId 只需传入您要传递给配置文件的用户 ID,稍后在配置文件组件中您可以获得此 ID 作为 this.props.location.state.id