【问题标题】:React Router - Mapping routes with 404 error pageReact Router - 使用 404 错误页面映射路由
【发布时间】:2020-06-21 21:08:14
【问题描述】:

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

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

上述用例有没有办法为所有非精确匹配的路由设置一个 404 组件。

我见过像这样的&lt;Switch&gt; 方法:https://reacttraining.com/react-router/web/example/no-match。如前所述,我更喜欢在路由配置文件中声明所有路由,包括路径、组件和面包屑名称。如果我沿着 Switch 路线走,那么路线配置仅用于面包屑并且变得不那么有用

【问题讨论】:

    标签: reactjs react-router react-router-dom react-router-redux


    【解决方案1】:

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

    如果你看一下renderRoutes 的实现,你会注意到它在内部使用了一个Switch 组件,这意味着你可以将你的“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: "*",
            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-configunless you have a very specific need 我不推荐使用它。

    【讨论】: