react-router v5-嵌套路由

时间:2019-10-10 16:28:42

标签: javascript reactjs react-router

即使查看SO答案,我也无法弄清楚。我的布局看起来像这样:

const Dashboard = (props) => (
  <div className={styles.views}>
    <Route
      to="/dashboard/reports/create"
      render={() => <ReportsForm {...props} />}
      exact
    />
    <Route
      to="/dashboard/reports"
      render={() => <Reports {...props} />}
      exact
    />
  </div>
);

const routes = [
  { path: '/', component: Home, exact: true },
  { path: '/dashboard', component: Dashboard },
  { path: '/about', component: About, exact: true },
  { path: undefined, component: Error404 },
];

const Routes = () => {
  return (
    <Switch>
      {routes.map((config, i) => {
        const key = `path-${config.path}`;
        return <Route key={key} {...config} />;
      })}
    </Switch>
  );
};
const App = compose(
  withRouter,
  connect(mapStateToProps),
)(() => {
  return (
    <Router history={history}>
      <IntlProvider>
        <Routes />
      </IntlProvider>
    </Router>
  );
})

我有一个仪表板组件,负责呈现多个标签,因此转到/dashboard/reports/create仅应渲染ReportsForm组件,转到/dashboard/reports仅应渲染Reports零件。目前,两种情况下都呈现。

我在做什么错了?

编辑 当我尝试在控制台中打印出match道具时,它给了我–也许这会有所帮助:

{
  "path": "/dashboard",
  "url": "/dashboard",
  "isExact": false,
  "params": {}
}

1 个答案:

答案 0 :(得分:1)

除了您指出用于声明to而不是path的错字

您可以将Dashboard个组件Route包裹在Switch

const Dashboard = (props) => (
  <div className={styles.views}>
   <Switch>
    <Route
      path="/dashboard/reports/create"
      render={() => <ReportsForm {...props} />}
      exact
    />
    <Route
      path="/dashboard/reports"
      render={() => <Reports {...props} />}
      exact
    />
   </Switch>
  </div>
);

如果这样不起作用,您甚至可以将路径用如下初始路径包装在Route中:

const Dashboard = props => (
  <div className={styles.views}>
    <Route path="/dashboard/reports">   // <------------------
      <Switch>
        <Route path="/dashboard/reports/create" render={() => <ReportsForm {...props} />} exact />
        <Route path="/dashboard/reports" render={() => <Reports {...props} />} exact />
      </Switch>
    </Route>
  </div>
);

这是我刚刚创建的工作示例解决方案:https://stackblitz.com/edit/react-uih91e-router-nested?file=index.js