React Router v6 - 检查子元素是否处于活动状态/<Outlet/> 会 return 一个组件吗?

React Routger v6 - Check wether child element is active / <Outlet/> would return a Component?

美好的一天, 你能帮我解决我在 react-router v6 的嵌套元素,特别是子元素方面的问题吗?

假设我有这个路由

<Routes>
    <Route path="customer" element={<CustomerIndex />} >
         <Route path=":customeId" element={<CustomerDetail />} />
         <Route path="create" element={<CustomerForm />} />
    </Route>
</Routes>

和“CustomerIndex”组件

function CustomerPage(){
    const {customerId} = useParams();
    return (
            <>
               //.....Bla bla bla index table etc etc etc end of thinking capacity        
               <ComponentToDisplayModal display={Boolean(customerId)} >
                    <Outlet />
               </ComponentToDisplayModal>
            </>
         );
}

现在,如果我转到“/customer/3”,CustomerIndex 将显示模态组件 (display=true),因为“customerId”常量由 useParams

定义

但是如果我想通过导航到“/customer/create”来显示“CustomerForm”组件,当然,“ComponentToDisplayModal”不会显示,因为 customerId 为空。

所以,当然,我想用这个代替

const display = Boolean(customerId) || isAnyChildPath;
.....
<ComponentToDisplayModal {...{display}}>

现在,如果路径是“/customer/*”,我如何将“isAnyChildPath”常量设置为“TRUE”,如果路径是“/customer”,我如何设置“FALSE”,或者,检查是否会 return 一个组件(例如“/customer/create”、“/customer/4”),或者不是(“/customer”)?

目前,我只是使用

的手动方法
const location = useLocation();
const display = Boolean(customerId) || location.pathname === "/customer/create"

但我想知道是否存在更优雅的方法,以防将来我需要添加其他几个静态子对象。

非常感谢。

我认为您可以通过使用 useMatch 挂钩来简化子路由检查,并检查当前路径是否与任一子路由匹配,而不是通过任何路由路径参数进行测试。

useMatch

declare function useMatch<ParamKey extends string = string>(
  pattern: PathPattern | string
): PathMatch<ParamKey> | null;

Returns match data about a route at the given path relative to the current location.

思路是,当路由匹配时返回定义的匹配对象,否则为non-matches返回null

"/customer/:path" 可以同时匹配 "/customer/:id""/customer/create".

示例:

function CustomerPage(){
  const isMatch = useMatch("/customer/:path");

  return (
    <>
      //.....Bla bla bla index table etc etc etc end of thinking capacity        
      <ComponentToDisplayModal display={Boolean(isMatch)} >
        <Outlet />
      </ComponentToDisplayModal>
    </>
  );
}