【问题标题】:Different component on the same ID ReactJS同一个 ID ReactJS 上的不同组件
【发布时间】:2018-10-01 22:58:36
【问题描述】:

是否可以在相同 id 的两个不同组件上调用 react-router?这是我的路由器:

<Route path="/Sessions" exact component={Sessions}/>
<Route path="/Sessions/:id" exact render={props => <GeekSessions{...props} /> }/>

我需要在此架构上添加其他组件 (GeekDashSession)。

如果你有任何想法。

【问题讨论】:

  • 不清楚你真正想要什么。给我们更多细节。
  • 在我的应用程序中,我需要重定向 Sessions/:id 两个组件。已经定义并工作的 GeekSession 和另一个(GeekDashSession),因为我的用户具有不同的角色,当一个在 GeekSession 上重定向时,另一个需要在另一个上重定向。不知道是不是更清楚...
  • 知道了。你在道具上有“用户角色”吗?
  • 没有。我不是为了从我的用户上获取 user_role 并使用它....

标签: reactjs react-router nav


【解决方案1】:

根据您在上面的 cmets 中所说,最好的选择是创建一个 Wrapper 组件,该组件将获取 user_role 并决定要渲染哪个组件。像这样的:

Wrapper.js

class Wrapper extends React.Component {
  state = {
    user_role: null
  }
  componentDidMount() {
    // get user role from api with the user id
    this.setState({ user_role: role_from_api });
  }
  render() {
  return !user_role ?
    "Loading ..."
    : user_role === "geek" ?
    <GeekSessions {...this.props} />
    :
    <GeekDashSession {...this.props} />
  }
}

然后你会像这样使用它:

&lt;Route path="/Sessions/:id" exact render={props =&gt; &lt;Wrapper {...props} /&gt; }/&gt;

【讨论】:

  • 好的,我明白了。我要测试一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多