【问题标题】:Prevent component render in specific page react-router防止组件在特定页面 react-router 中呈现
【发布时间】:2021-03-27 23:38:15
【问题描述】:

“导航栏”和“页脚”会在每个组件的页面上呈现。有没有办法防止在“用户”组件中呈现“页脚”?

App.js

   <Router>
    <Route>
      <Navbar />
      <Switch>
        <Route path='/' exact component={Home} />
        <Route path='/About' exact component={About} />
      </Switch>
      <Footer />
    </Route>

    <Route>
      <Route path='/user' component={User} />
    </Route>

    <Route path='*' component={NotFound} />
  </Router>

【问题讨论】:

标签: reactjs routes react-router jsx


【解决方案1】:

&lt;Router&gt; 移动到index.js 文件,如下所示,以访问App.js 中的props.location

<Router>
  <App />
</Router>

在您的 App.js 文件中:

const App = ({ location }) => {
  return (
    <Route>
      <Navbar />
      <Switch>
        <Route path='/' exact component={Home} />
        <Route path='/About' exact component={About} />
      </Switch>
      {location.pathname !== '/user' && <Footer /> }
    </Route>
    <Route>
      <Route path='/user' component={User} />
    </Route>

    <Route path='*' component={NotFound} />
  )
}

此解决方案适用于 react-routerreact-router-dom v5+

【讨论】:

  • 能否请您编辑代码并解释得更清楚..
猜你喜欢
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 2017-11-19
相关资源
最近更新 更多