首页 > 解决方案 > 根据路径中的参数渲染组件

问题描述

对于我的项目,我想在 url.com/username 处呈现用户页面。如果登录用户的用户名与参数匹配,那么它将呈现他们的个人资料页面。所以在我的路由器中我有这条路线......

<Route path="/:username" exact component={/* Profile or User's Page */}>

我还有其他路由,其中​​组件是有条件的,并且我在组件中使用了三元组,但是在这种情况下,它将基于 :username 参数。有没有办法在组件标签中访问该值?或者我应该在组件标签中有某种 HOC,我可以将 :username 参数与经过身份验证的用户名进行比较,然后返回 Profile 或 UserPage 组件?

标签: reactjsreact-router

解决方案


您可以使用组件属性访问 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 ...
       })} 
/>

推荐阅读