React Router-映射具有404错误页面的路由

问题描述 投票:0回答:1

我目前正在使用React Router。与<Switch>选项相反,我更喜欢使用路由配置文件的语法以及在路由数组上进行映射以呈现Route的语法。

{routes.map(route => {
        return (
          <PrivateRoute
            key={route.path}
            path={route.path}
            exact
            component={route.component}
          />
        );
      })}

上述用例是否有办法为所有不完全匹配的路由都提供404组件。

我已经看到像这样的<Switch>方法:https://reacttraining.com/react-router/web/example/no-match。如前所述,我更喜欢在路由配置文件中声明所有路由,包括路径,组件和面包屑名称。如果我沿Switch路由走,则该路由配置仅用于面包屑,变得不太有用

reactjs react-router react-router-dom react-router-redux
1个回答
0
投票

如果要在配置文件中定义路由,则可能应该使用react-router-config(它也是react-router的一部分)

[如果您窥视renderRoutes的实现,那么您会注意到它在内部使用了renderRoutes组件,这意味着您可以将“ 404”路由放在列表的末尾,并且应该回退如果没有其他匹配项,例如:

Switch

您也可以实现这样的组件const routes = [ { component: Root, routes: [ { path: "/", exact: true, component: Home }, { path: "/child/:id", component: Child, routes: [ { path: "/child/:id/grand-child", component: GrandChild } ] }, { path: "*", component: NotFound, }, ] } ]

RedirectToNotFound

然后像这样设置您的配置文件:

const RedirectToNotFound = () => <Redirect to="/404" />;

完全公开:我从未使用过const routes = [ { component: Root, routes: [ { path: "/", exact: true, component: Home }, { path: "/child/:id", component: Child, routes: [ { path: "/child/:id/grand-child", component: GrandChild } ] }, { path: "/404", component: NotFound }, { path: "*", component: RedirectToNotFound, }, ] } ] react-router-config,我不推荐使用它。

© www.soinside.com 2019 - 2024. All rights reserved.