【问题标题】:React router only show Navigation component if the current path is on any of the valid routes如果当前路径在任何有效路由上,React 路由器仅显示导航组件
【发布时间】:2019-12-07 23:59:01
【问题描述】:

对于无效路由,我想显示NotFound 组件,但也不显示Navigation 组件:

const Layout: React.FunctionComponent = () => {
  return (
    <Router>
      <Navigation />
      <Switch>
        <Route path="/explore" exact>
          <ExploreIndex />
        </Route>
        <Route path="/explore/:id" exact>
          <ExploreShow />
        </Route>
        <Route path="/" exact>
          <Home />
        </Route>

        <Route component={NotFound} />
      </Switch>
    </Router>
  );
};

如果我转到/aaaaaaa,我的NotFound 组件会加载,但我的Navigation 也会加载。我怎么能没有 Navigation 为这些路线渲染?

【问题讨论】:

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


    【解决方案1】:

    将其渲染为另一条路线怎么样?

    <Route path={['/explore', '/explore/:id', '/']} exact component={Navigation} />
    

    如果路由与path 数组中列出的任何路由都不匹配,则不会呈现。

    【讨论】:

      【解决方案2】:

      您可以在特定组件而不是 app.js 中添加 NavigationBar。因此,例如,如果有一个关于页面,请将 NavigationBar 放在组件顶部

      【讨论】:

        猜你喜欢
        • 2017-12-21
        • 2018-08-20
        • 1970-01-01
        • 2020-01-21
        • 2016-12-29
        • 2017-08-28
        • 2021-10-09
        • 2018-01-20
        • 2022-11-06
        相关资源
        最近更新 更多