react-router错误路由匹配规则?

const routes = [
  { path: "/home/ooo", component: Child, name: "home/0000" },
  {
    path: "/home",
    component: Home,
    exact: false,
    name: "home页面",
    routes: [
      {
        path: "/home/child",
        exact: false,
        component: Child,
        name: "home的子页面",
      },
    ],
  },
  {
    path: "/js",
    component: Js,
    name: "js页面",
  },
  {
    path: "*",
    component: 404,
    name: "404",
  },
];

我的路由配置, 希望根据这个配置封装路由组件

希望我在访问 /home/child/xxx 这种米有匹配的路由时,自动匹配到 404 页面, 该怎么封装

阅读 2.5k
1 个回答
const renderRoutes = (routes) => {
  return (
    <Switch>
      {routes.map((route, index) => {
        if (route.routes) {
          return (
            <Route
              key={index}
              path={route.path}
              exact={route.exact}
              render={(props) => (
                <route.component {...props}>
                  {renderRoutes(route.routes)}
                </route.component>
              )}
            />
          );
        } else {
          return <Route key={index} path={route.path} exact={route.exact} component={route.component} />;
        }
      })}
    </Switch>
  );
};

const App = () => {
  return (
    <Router>
      <Switch>
        {renderRoutes(routes)}
        <Route component={NotFound} /> {/* 通配符路由,渲染404组件 */}
      </Switch>
    </Router>
  );
};

把 /home/child 设置 exact={true}

const routes = [
  { path: "/home/ooo", component: Child, name: "home/0000" },
  {
    path: "/home",
    component: Home,
    exact: false,
    name: "home页面",
    routes: [
      {
        path: "/home/child",
        exact: true,
        component: Child,
        name: "home的子页面",
      },
    ],
  },
  {
    path: "/js",
    component: Js,
    name: "js页面",
  },
];

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏