在auth的情况下,React-router多个组件onEnter?

时间:2017-01-07 08:28:02

标签: javascript reactjs redux react-router flux

我正在为一条路径创建一个包含2个组件的应用。这是我的路线:

<Router history={hashHistory}>
    <Route path="/" component={AppContainer} onEnter={requireEnter}>
        <Route path="/homepage" component={HomePage} />
        <Route component={MainPage} onEnter={requireAuth}>
            <Route path="/home" component={DashBoard} />
        </Route>
    </Route>
</Router>

在这种情况下,我使用AppContainer组件进入我的应用程序。而不是我希望该组件应该是我的选择,因为我有一个主页path="/"

现在onEnter={requireEnter}处理以下情况:

function requireEnter (nextState, replace) {
    if (nextState.location.pathname == "/") {
        if (checkLoggedIn()) {
            replace({
                pathname: '/home'
            })
        } else {
            replace({
                pathname: '/homepage'
            })
        }
    }
}

但我想要这样的事情:

function requireEnter (nextState, replace) {
    if (nextState.location.pathname == "/") {
        if (checkLoggedIn()) {
            //component should be AppContainer and redirect to '/home'
        } else {
            //component should be home page
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你可以添加一个没有组件的路由,在另一个类似的情况下使用它:

<Route path="/" onEnter={requireEnter}>
  <Route path="home" component={AppContainer}>
      <IndexRoute component={HomeContainer} />
  </Route>
  <Route path="homepage" component{HomePageContainer}>
  </Route>
</Route>

然后像往常一样:

function requireEnter (nextState, replace){
  if(nextState.location.pathname=="/"){
      if(checkLoggedIn()){
         replace({
              pathname: '/home'
          });
      }else{
         replace({
              pathname: '/homepage'
         });
      }
  }
}