【问题标题】:react-router: Showing/Hiding a component based on Path matchedreact-router:根据匹配的路径显示/隐藏组件
【发布时间】:2018-05-09 19:43:58
【问题描述】:

我正在使用反应路由器 v4 和反应 v16。需要一些组件仅安装一次(第一次渲染时),但根据路由器路径匹配进行渲染。 (一个这样的用例是显示一个菜单项单击的报告,并且在以后的调用中,显示的报告不需要再次获取)。

使用 Switch 或仅使用普通 Route 组件——当该组件不在路径中时,该组件将被卸载。

目前,我正在这样做(解决了手头的问题):

<main>
  <Route exact path="/" component={Home} />
  <WrapRoute exact path="/about" component={About} />
</main>

const WrapRoute = ({path, ...rest}) => (
  <div style={{display: rest.location.pathname == path ? "block" : "none"}}>
    <Route {...rest} />
  </div>
)

但我不认为直接验证 location.pathname 是个好主意。我想要'Route'组件来处理这个。

我想要处理这种情况的建议(以不会再次重新安装组件的方式)。欢迎提供解决方案或不同的模式来解决这个问题。

【问题讨论】:

    标签: react-router


    【解决方案1】:

    虽然我不确定,如果有更好的模式可以解决这个问题——下面的代码比提供的更好。

    更新:

    虽然可以调用 matchPath 函数,但我才意识到调用“children”参数是一个更好的选择。

      <Route exact path="/dc/:id" children={({ match, ...rest }) => (
        <div style={{display: match && match.params.id === id.toString()
          ? "block"
          : "none"
        }}>
          <Component {...rest} match={match} />
        </div>
      )} />
    

    之前的解决方案:

    react-router 的 matchPath 函数可以准确识别——这条路径是否匹配。

    <main>
      <Route exact path="/" component={Home} />
      <WrapRoute exact path="/about" component={About} />
    </main>
    
    ......
    
    import { matchPath } from 'react-router'
    
    const WrapRoute = ({path, exact, ...rest}) => (
      <div style={{display: matchPath(rest.location.pathname, { path, exact })
        ? "block"
        : "none"
      }}>
        <Route {...rest} />
      </div>
    )
    

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 2020-05-09
      • 2022-10-25
      • 2017-10-26
      • 1970-01-01
      • 2016-12-23
      • 2018-05-22
      • 2019-04-13
      • 2018-12-18
      相关资源
      最近更新 更多