【问题标题】:Having route "/" show a different component depending on if user is authed让路由“/”根据用户是否经过身份验证显示不同的组件
【发布时间】:2015-11-06 02:34:43
【问题描述】:

我想要一条路线“/”:

  • 如果经过身份验证 -> 将用户带到主页(以下示例中的 Pages.Feed)
  • 如果未经过身份验证 -> 将用户带到 Landing(下例中为 Pages.Landing)

基本上,复制 facebook.com 或 twitter.com 的行为。

我想在路由级别做到这一点,而不是有一个构成逻辑的组件。

现在我有:

function requireAuth(nextState, replaceState) {
  if (!store.getState().currentUser.nick) {
    replaceState({ nextPathname: nextState.location.pathname }, '/landing');
  }
}

ReactDOM.render(
<Provider store={store}>
  <Router history={history}>
    <Route component={Containers.App}>
      <Route component={Containers.LandingLayout}>
        <Route path="landing" component={Pages.Landing} />
        <Route path="login" component={Pages.LogIn} />
        <Route path="signup" component={Pages.SignUp} />
      </Route>
      <Route path="/" component={Containers.AppLayout}>
        <IndexRoute component={Pages.Feed} onEnter={requireAuth}/>
        <Route path="about" component={Pages.About} />
        <Route path="help" component={Pages.Help} />
        <Route path=":nick" component={Pages.Profile} />
        <Route path=":nick/:slug" component={Pages.List} />
      </Route>
    </Route>
  </Router>
</Provider>,
document.getElementById('listlogs')
);

如果经过身份验证,“/”会将用户带到他的主页 (Pages.Feed),否则会将用户重定向到“/landing”。在这里,我需要一条我想避免的着陆的特定路线。我希望它是“/”。

使用:

component={authLogic ? Pages.Feed : Pages.Landing}

不是解决方案。它最初会工作,即如果用户未登录,应用程序将加载登陆,如果用户登录,则加载提要页面。但是,由于 React 路由器应用程序已经呈现,到组件的映射不会一旦用户在前一种情况下登录或在后一种情况下退出,就可以工作。以某种方式重新渲染路由是否有意义?有没有更好的解决方案?

【问题讨论】:

    标签: web-applications reactjs react-router


    【解决方案1】:

    使用路由器执行此操作的方法是在着陆页上方的路由上使用getChildRoutes,或者在着陆页的路由上使用getComponent

    这些钩子让您能够运行一些逻辑,然后使用所需的子路由或组件进行回调。

    例如,你可以这样做:

    <Route path="foo" getComponent={(_, cb) => cb(authed ? Page1 : Page2)} />
    

    更多详情请见https://github.com/rackt/react-router/blob/v1.0.0-rc4/docs/guides/advanced/DynamicRouting.md

    【讨论】:

    • 你有什么例子吗?我看不出延迟加载如何帮助我解决这个问题
    • 我在答案中添加了一个示例。
    • 我可以在 IndexRoute 上使用 getComponent 吗?
    【解决方案2】:

    在组件中做对我来说很有意义,这是您根据应用状态做出关于渲染什么的其他类似决定的地方。

    const App = React.createClass({
      render() {
        return authed ? <AppLayout/> : <Landing/>
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 2017-09-11
      • 2018-07-30
      • 2011-08-09
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多