reactjs - 根据路径中的参数渲染组件
问题描述
对于我的项目,我想在 url.com/username 处呈现用户页面。如果登录用户的用户名与参数匹配,那么它将呈现他们的个人资料页面。所以在我的路由器中我有这条路线......
<Route path="/:username" exact component={/* Profile or User's Page */}>
我还有其他路由,其中组件是有条件的,并且我在组件中使用了三元组,但是在这种情况下,它将基于 :username 参数。有没有办法在组件标签中访问该值?或者我应该在组件标签中有某种 HOC,我可以将 :username 参数与经过身份验证的用户名进行比较,然后返回 Profile 或 UserPage 组件?
解决方案
您可以使用组件属性访问 URL 参数match.params.:param
<Route
path="/:username"
component={Component}
/>
const Component = ({ match }) => (
<div>
<h3>{match.params.username}</h3>
</div>
);
如果要访问参数内的component
参数,例如可以使用匿名组件(或者只使用一个组件,专门用于确定将使用哪个子组件)。
<Route path="/:username"
component={({match} => {
if(match.params.username == this.props.username) {
return <SomeComponent />
} else ...
})}
/>
推荐阅读
- python - 如何仅选择数值数据类型并将它们保存在python中的数组中?
- javascript - 将单选按钮更改为下拉菜单
- windows - 如何使用 TCP/IP 有效地发送标头 + 缓冲区?
- service - TFS 2018 - 字段清洁
- c# - ML.NET TrainTestSplit random seed
- c# - 没有 SQL Server 的 SSIS
- openssl - openssl base64 和 javascript 的 btoa 的区别
- javascript - 如何在不上传的情况下访问图像并将其显示在 IMG 标签中
- python - 从文件中提取一个热编码到数据集中
- c# - .Net Core 2.1 Web API 同时使用 JWT 和 JWT Cookie