OKCUPID,REDDIT如何使用React路由器处理用户配置文件路由



我正在尝试设置类似的结构,/profile在其中将您带到您的个人资料并允许您编辑信息。/profile/:UserId将带您进入他人的个人资料,并允许您发送消息但不得编辑(显然(。我在想类似于此逻辑的东西:

<Route path='profile'> 
  <IndexRoute component={requireAuth(Profile)} />
  <Route path=':userId' component={requireAuth(Profile)} />
</Route> 

以及在Profile组件中,做

之类的事情
if (this.props.params.userId !== this.props.currentUser.id) 
  <SendMessage toUser={this.props.params.userId} /> 

这会变得笨拙,因为无论是当前用户还是其他配置文件,几乎都会对几乎所有元素进行大量验证检查。有没有一种"正确"的方法来执行此操作?

是。您自己的个人资料页面(/配置文件(和其他页面(/profile/:userId(的组件应为不同的组件(可能具有相似的标记(。例如,/配置文件的组件不需要<SendMessage/>等。

<Route path='profile' onEnter={requireAuth}> 
  <IndexRoute component={ProfileSelfComponent} />
  <Route path=':userId' component={ProfileOtherComponent} />
</Route>

requireAuth将处理用户是否已登录等等。

您唯一想要的是,当用户试图导航到自己的/profile/:profile Id时,它会将其路由到他自己的个人资料

这可以通过将类似的内容添加到ProfileOtherComponent

来完成
componentWillMount(){
    if (this.props.params.userId === this.props.currentUser.id) 
         browserHistory.push('/profile')
}

最新更新