From 084bf89b8a15d939b876cd17f009efdf66fa045f Mon Sep 17 00:00:00 2001 From: wang <1509326266@qq.com> Date: Mon, 9 Sep 2024 03:22:56 +0800 Subject: [PATCH] feat(projects): support add parent when add route --- packages/simple-router/src/router.tsx | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/packages/simple-router/src/router.tsx b/packages/simple-router/src/router.tsx index a83d5e9..8e01f9b 100644 --- a/packages/simple-router/src/router.tsx +++ b/packages/simple-router/src/router.tsx @@ -32,7 +32,7 @@ class CreateRouter { reactRoutes: RouteObject[] = []; initRoute = false; reactRouter: RemixRouter; - listeners: (() => void)[] = []; + private listeners: (() => void)[] = []; initReactRoutes: RouteObject[] = []; private matcher: CreateRouterMatcher; currentRoute = START_LOCATION_NORMALIZED; @@ -79,24 +79,29 @@ class CreateRouter { * * @param routes - An array of elegant constant routes. */ - addReactRoutes(routes: ElegantConstRoute[]) { + addReactRoutes(parentOrRoute: ElegantConstRoute[] | string, elegantRoutes?: ElegantConstRoute[]) { // Flatten nested routes - const flattenRoutes = routes.flat(); + let parent: string | null = null; + let routes: ElegantConstRoute; + if (typeof parentOrRoute === 'string') { + parent = parentOrRoute; + routes = elegantRoutes; + } else { + routes = parentOrRoute; + } - flattenRoutes.forEach(route => { - const matcher = this.matcher.getRecordMatcher(route.name); - if (matcher) return; + const flattenRoutes = routes.flat(); + const reactRoutes = flattenRoutes.map(route => { // Add route this.#addRoute(route); // Transform to react-router route const reactRoute = this.getReactRoutes(route); - // Add to react-router's routes this.reactRoutes.push(reactRoute); + return reactRoute; }); - - // Update react-router's routes - this.#changeRoutes(); + // Add to react-router's routes + this.reactRouter.patchRoutes(parent, reactRoutes); } #changeRoutes() { @@ -113,6 +118,7 @@ class CreateRouter { removeRoute(name: string) { const matched = this.matcher.getRecordMatcher(name); if (!matched) return; + if (matched.parent) { const parentNames = findParentNames(matched.parent); let routes = this.reactRoutes; @@ -286,6 +292,7 @@ class CreateRouter { this.reactRoutes.length = 0; // Resets the route matcher so it can begin matching new routes again. this.matcher.resetMatcher(); + this.#changeRoutes(); } /**