路径不匹配时反应路由器渲染菜单 [英] react-router render menu when path does not match

查看:35
本文介绍了路径不匹配时反应路由器渲染菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-router 并且我想在用户不在根目录中并且不在/login 路径中时呈现菜单组件.这是我目前所拥有的

 <div><路线精确路径=/"渲染={道具=>(<LoginContainer {...props} setTitle={this.setTitle}/>)}/><Route path='/landing' component={LandingComponent}/>

负责不在/"位置呈现 TopMenuComponent 组件,但是当用户位于/login 路径时如何避免它呈现 TopMenuComponent?我总是可以创建另一个组件并将其包装起来,但我认为仅此而已.

解决方案

最简单的实现

使用三元表达式短路评估 有条件地呈现您的基于 location.pathname 的组件,如下所示:

<路由渲染={({位置})=>['/', '/login'].includes(location.pathname)?<组件/>: 空值}/>

正则表达式实现

React Router 对路径字符串 依赖于 path-to-regexp@^1.7.0.

因此,您可以使用 routes 不对某些路径进行渲染>正则表达式.

以下实现应呈现给定任何 path 值,条形 "/""/login":

//在字符串中使用正则表达式.<路由路径={"^(?!.*(\/|\/login)).*$"} component={TopMenuComponent}/>//使用显式正则表达式.<Route path={new RegExp('^(?!.*(\/|\/login)).*$')} component={TopMenuComponent}/>

I'm using react-router and I want to render a menu component when the user is not in the root and not in the /login path. This is what I have so far

        <Route path="/:subpath" component={TopMenuComponent} />
        <div>
            <Route
                exact path="/"
                render={props => (
                    <LoginContainer {...props} setTitle={this.setTitle} />
                )}
            />               
            <Route path='/landing' component={LandingComponent} />
        </div>

takes care of not rendering the TopMenuComponent component in the '/' location, however how do I avoid it rendering TopMenuComponent when the user is in the /login path? I could always create another component and wrap it up, but I think that is too much just for this.

解决方案

Simplest Implementation

Use a ternary expression or short-circuit evaluation to conditionally render your component based on location.pathname, like so:

<Route 
    render={({ location }) => ['/', '/login'].includes(location.pathname)
        ? <Component/>
        : null
    }
/>

Regex Implementation

React Router's matching of path strings relies on path-to-regexp@^1.7.0.

As a result, you can instruct routes to not render for certain paths using regular expressions.

The following implementations should render given any path value, bar "/" and "/login":

// With Regex Inside String.
<Route path={"^(?!.*(\/|\/login)).*$"} component={TopMenuComponent}/>

// With Explicit Regex.
<Route path={new RegExp('^(?!.*(\/|\/login)).*$')} component={TopMenuComponent}/>

这篇关于路径不匹配时反应路由器渲染菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆