美好的一天, 您能帮我解决有关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”,我如何将“isAnyChildPath”常量设置为“TRUE”,或者检查是否会返回组件(例如.“/customer/create”、“/customer/4”),还是不是(“/customer”)?
目前我只使用手动方法
const location = useLocation();
const display = Boolean(customerId) || location.pathname === "/customer/create"
但是我想了解是否存在更优雅的方法,以防将来我需要添加其他几个静态子项。
非常感谢。
最佳答案
我认为您可以使用 useMatch
Hook 稍微简化子路由检查,并检查当前路径是否与任一子路由匹配,而不是通过任何路由路径参数进行测试。
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.
这个想法是,当路由匹配时,返回定义的匹配对象,否则,如果不匹配,则返回 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>
</>
);
}
关于javascript - React Router v6 - 检查子元素是否处于事件状态/<Outlet/>会返回组件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71494828/