【问题标题】:Show a navigation component on all routes except the root在除根以外的所有路由上显示导航组件
【发布时间】:2021-01-22 02:26:27
【问题描述】:

我需要在除根路线之外的所有路线上显示主导航。如果我要在所有路线上显示,我会这样做:

class App extends Component {
    render() {
        return (
            <Container className="App" maxWidth="lg">
                <Grid className="app-container">
                    <MainNav /> 
                    <Switch>
                        <Route exact path="/" component={Home} />
                        <Route
                            exact
                            path="/some-other-route"
                            component={SomeOtherComponent}
                        />
                        ...
                    </Switch>
                </Grid>
            </Container>
        );
    }
}

我可以为所有其他路线制作一个包装器组件并将其放在那里,但我能想到的任何解决方案似乎都是错误的,可能有更好的方法。有没有更好的办法?

【问题讨论】:

  • 你想动态显示你的路线吗?
  • 是的,会有一条动态路由

标签: reactjs react-router


【解决方案1】:

也许你可以使用这个代码。

以下代码的灵感来自nextjs 页面路由。 您只需在 ~/pages/ 上添加您的路线,它就会动态导入它们。

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

function DynamicRoutes() {
  return (
    <BrowserRouter>
      <Switch>
        <Route
          path="/"
          render={({ history, location, match })=>{
            const Page = React.lazy(()=>{
              return import('./pages'+location.pathname).catch((e) => {
                if (/not find module/.test(e.message)) {
                  return import("./pages/NotFound");
                }
                if (/Loading chunk \d+ failed/.test(e.message)) {
                  window.location.reload();
                  return;
                }
                throw e;
              })
            });
            return (
              <React.Suspense fallback ={<div>Loading...</div>}>
                <Page />
              </React.Suspense>
            )

          }}
        />
      </Switch>
    </BrowserRouter>
  )
}
export default DynamicRoutes;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2021-12-20
    • 2021-01-30
    • 2017-10-03
    • 2017-02-19
    • 2017-04-21
    相关资源
    最近更新 更多