【问题标题】:Do not render certain components on certain routes不要在某些路由上渲染某些组件
【发布时间】:2017-09-30 23:48:36
【问题描述】:

在我的index.js 中,我有一个带有Router 的渲染方法,其中包含显示组件的Routes:

<Router>
  <div>
    <Headers />
    <ToggleSwitch />
    <Route exact path="/" component={Home} />
    <Route path="/library" component={Library} />
    <Range />
  </div>
</Router>

这很好用。

但是,在Library 路线上,我不想显示&lt;Headers /&gt; 或&lt;ToggleSwitch /&gt;。

所以我希望能够应用以下方法,例如:

const isHeaderRoute = (!route.includes('library'))

{isHeaderRoute && (
  <Headers />
  <ToggleSwitch />
)}

为此,我可能需要访问 URL 路径。

如何使用 React Router 实现这一点?

【问题讨论】:

标签: reactjs react-router react-router-v4


【解决方案1】:
<Router>
  <div>
    <Route exact path="/" component={Home} />
    <Route path="/library" component={Library} />
    <Range />
  </div>
</Router>

从路由中移除Headers 和ToggleSwitch 组件,然后将它们放入Home 组件中。

如果你想在Router 中通过window.location.pathname 获取路径名并执行示例中的操作:

const isHeaderRoute = (!window.location.pathname.includes('library'))

{isHeaderRoute && (
  <Headers />
  <ToggleSwitch />
)}

window.location.pathname 是 Javascript 方法,而不是 react-router 方法。您的建议在 react-router 中是不可能的,因为检查需要在路由器外部进行,无法访问只能在路由器内部访问的路由器路径(通过子组件等)。

【讨论】:

    【解决方案2】:

    我刚遇到同样的问题,用同样的答案解决了as posted here

    将您的 &lt;Route /&gt; 包装在包含 &lt;Headers /&gt; 和 &lt;ToggleSwitch /&gt; 的组件中(反之亦然,这对您的代码更有意义)

    例如。 (ES6 使用react-router-v4)

    const SpecialRoute = ({ component: Component, ...rest }: {component: any}) => (
      <div>
        <Headers />
        <ToggleSwitch />
        <Route
          {...rest}
          render={(props: {location: string}) => (
            <Component {...props} />
          )}
        />
      </div>
    )
    
    <Router>
      <div>
        <SpecialRoute exact path="/" component={Home} />
        <Route path="/library" component={Library} />
        <Range />
      </div>
    </Router>
    

    Further reading

    【讨论】:

      猜你喜欢
      • 2022-08-02
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      相关资源
      最近更新 更多