如何使用react router dom显示嵌套组件?

时间:2018-11-12 18:37:53

标签: reactjs react-router-dom

在我的应用程序中,我有几个用react router dom定义的路由。 所有路由都可以正常工作,但是嵌套路由不会显示,而是转到错误页面。

  

这是我的索引路线

const initialRoutes = [
{
 path: "/",
 component: Home
},
{
 path: "/login",
 component: Login
},
{
 path: "/dashboard",
 component: Dashboardlayout
},
{
 path: "*",
 component: Error
} /* And so on. */
];
export default initialRoutes;

此处的Dashboardlayout由其他与Dashboard相关的路线组成

  

仪表板布局页面

import Dashboard from "../pages/DashboardPages/Dashboard";
import Create from "../pages/DashboardPages/Create";

var dashRoutes = [
  {
    path: "/",
    name: "Dashboard",
    icon: "nc-icon nc-bank",
    component: Dashboard
  },
  {
    path: "/dashboard/create",
    name: "Dashboard",
    icon: "nc-icon nc-bank",
    component: Create
  }
];
export default dashRoutes;
  

我的App.js页面是,它通过initialRoutes文件进行映射。

render() {
    const routeComponents = RootRoutes.map(({ path, component }, key) => (
      <Route exact path={path} component={component} key={key} />
    ));
    return (
      <div className="main-body">
        <BrowserRouter>
          <Switch>{routeComponents}</Switch>
        </BrowserRouter>
        {this.state.menuModal ? (
          <MenuToggle toggleMenuModal={() => this.toggleMenuModal()} />
        ) : (
          ""
        )}
      </div>
    );
  }

问题是当URL为localhost:3000 / dashbaord时它显示仪表板组件,但是当url为localhost:3000 / dashboard / create时将我重定向到“未找到/错误”页面。为什么会这样?

1 个答案:

答案 0 :(得分:0)

exact prop阻止/dashboard路径在/dashboard/create路径上匹配。

对于具有嵌套路由的父路由,不应使用exact