GOAL:在除 /search
和所有 /:id
之外的所有路由(例如,用户名路由)上呈现导航组件
这是我根据宽度有条件地呈现 Navigation
组件的代码:
let { pathname } = useLocation();
const isTallEnough = useMedia("(min-width: 1000px)");
if (!user.uid && pathname == "/" && !isTallEnough) return null;
if (!user.uid && pathname === "/search" && !isTallEnough) return null;
如何确保在 /:id
路线上导航组件不会呈现?
答案 0 :(得分:0)
假设您使用 React Router,您可以使用 useRouteMatch
钩子。这样你就可以设置如下:
// outside of component
function useShouldRenderComponent() {
let is_search = useRouteMatch('/search');
let is_user_id = useRouteMatch('/user/:id');
let is_wide_enough = useMedia("(min-width: 1000px)")
// add more, if needed
return !(is_search || is_user_id) && is_wide_enough;
}
// in component
let shouldRenderComponent = useShouldRenderComponent();
if (!shouldRenderComponent) return null;
return <Navigation/>