【问题标题】:React router 4 - detect if one of child route matches in a parent componentReact router 4 - 检测父组件中的子路由之一是否匹配
【发布时间】:2018-06-07 19:40:49
【问题描述】:

我正在使用 react router 4 来显示用户列表。当路由匹配\Users 时,组件Users 加载。在其中,我定义了一个 Route(用户详细信息),当 URL 匹配 \Users\:id 时加载它。

Users 页面有一个包含几列的网格/表格。

render(){
    const {users, flags} = this.props;
    return (
        <div>
            <h3>Users</h3>
            <div className="col-md-12">
                <UsersGrid users={this.state.users} />
            </div>
            <Route path="/users/:id" component={UserDetail} />
        </div>
    )
}

我想要的是如果用户详细信息路由处于活动状态,然后缩小用户网格(例如应用类 col-md-4)并在其右侧显示用户详细信息。

但我不确定如何检测子路由是否处于活动状态,以便有条件地将类应用于元素。我尝试使用this.props.children,但它始终未定义。

【问题讨论】:

    标签: reactjs react-router react-redux


    【解决方案1】:

    你可以使用 react-router 中的matchPath

    import { matchPath } from 'react-router'
    
    render(){
        const {users, flags, location } = this.props;
        const match = matchPath(location.pathname, {
           path: '/users/:id',
           exact: false,
           strict: false
        })
        return (
            <div>
                <h3>Users</h3>
                <div className="col-md-12">
                    <UsersGrid users={this.state.users} />
                </div>
                <Route path="/users/:id" component={UserDetail} />
            </div>
        )
    }
    

    【讨论】:

      【解决方案2】:

      如果 url 显示在地址栏中,那么您可以使用 window.location 检查它是否在 /user 之后包含类似 id 的字符串,然后使用条件检查执行操作:

              if(/user/{anyid}) {
               *your condition action*
              } else {
               *else action*
              }
      

      您可以使用字符串正则表达式来匹配 id。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-20
        • 2023-03-29
        • 1970-01-01
        • 2017-09-08
        • 2017-04-24
        • 1970-01-01
        • 2016-09-02
        • 2017-10-26
        相关资源
        最近更新 更多