Switch内的嵌套路由

时间:2019-01-26 18:32:44

标签: reactjs react-router

在我的 index.js 上,我有以下内容

var indexRoutes = [
    { path: "/", name: "Homepage", component: Home},
    { path: "/dashboard", name: "Dashboard", component: Dashboard },
];

ReactDOM.render(
  <HashRouter>
    <Switch>
      {indexRoutes.map((prop, key) => {
        return <Route path={prop.path} component={prop.component} exact/>;
      })}
      <Route component={Homepage} />
    </Switch>
  </HashRouter>,
  document.getElementById("root")
);

基本上,Home组件将具有首页,登录名和注册名,如下所示:

<div className="app-container">
    <Header/>
    <Switch>
        <Route path="/" component={Visitor} exact/>
        <Route path="/register" component={Register} exact/>
        <Route path="/login" component={Login} exact />
        <Route component={NotFound}/>
    </Switch>
    <Footer/>
</div>

至此,一切正常。但是,当我尝试在仪表板上使用嵌套路由时,它们将不起作用。

const dashboardRoutes = [
  {
    path: "/dashboard",
    name: "Dashboard",
    icon: "pe-7s-graph",
    component: Dashboard
  },
  {
    path: "/dashboard/tours",
    name: "Tours",
    icon: "pe-7s-plane",
    component: Tours
  },
  {
    path: "/dashboard/user",
    name: "User Profile",
    icon: "pe-7s-user",
    component: UserProfile
  }] 

 render() {

    return (
      <div className="wrapper">
        <Sidebar {...this.props} />
        <div id="main-panel" className="main-panel" ref="mainPanel">
          <Header {...this.props} />
          <Switch>


              if (prop.redirect)
                return <Redirect from={prop.path} to={prop.to} key={key} />;
              else 
                return <Route path={prop.path} component={prop.component} exact />


            })}
          </Switch>
          <Footer />
        </div>
      </div>
    );
  }
}

/ register / login和/ dashboard都可以正常工作。但是,当我尝试访问(例如/ dashboard / user)时,它会从Home组件向我显示NotFound页面。

我在做什么错?谢谢。

1 个答案:

答案 0 :(得分:1)

您将exact参数用于/dashboard路由。根据{{​​3}},除/dashboard外,没有其他匹配项。您的index.js应该有return <Route path={prop.path} component={prop.component} />

path    location.pathname   exact   matches?
/one    /one/two            false   yes
/one    /one/two            true    no

编辑:根据您的递归方法,我会将exact参数放入数组中,如果为true,则进行渲染。

var indexRoutes = [
    { path: "/", name: "Homepage", component: Home, exact: true},
    { path: "/dashboard", name: "Dashboard", component: Dashboard, exact: false },
];

ReactDOM.render(
  <HashRouter>
    <Switch>
      {indexRoutes.map((prop, key) => {
        return <Route path={prop.path} component={prop.component} exact={prop.exact} />;
      })}
      <Route component={Homepage} />
    </Switch>
  </HashRouter>,
  document.getElementById("root")
);