ChatGPT解决这个技术问题 Extra ChatGPT

带有反应路由器 v4 / v5 的嵌套路由

我目前正在努力使用反应路由器 v4 嵌套路由。

最接近的示例是 React-Router v4 Documentation 中的路由配置。

我想将我的应用分成 2 个不同的部分。

一个前端和一个管理区域。

我在想这样的事情:

<Match pattern="/" component={Frontpage}>
  <Match pattern="/home" component={HomePage} />
  <Match pattern="/about" component={AboutPage} />
</Match>
<Match pattern="/admin" component={Backend}>
  <Match pattern="/home" component={Dashboard} />
  <Match pattern="/users" component={UserPage} />
</Match>
<Miss component={NotFoundPage} />

前端的布局和样式与管理区域不同。所以在首页的路线首页,关于等应该是子路线。

/home 应呈现在 Frontpage 组件中,而 /admin/home 应呈现在 Backend 组件中。

我尝试了其他一些变体,但总是以没有点击 /home/admin/home 结束。

最终解决方案:

这是我现在使用的最终解决方案。这个例子还有一个像传统 404 页面一样的全局错误组件。

import React, { Component } from 'react';
import { Switch, Route, Redirect, Link } from 'react-router-dom';

const Home = () => <div><h1>Home</h1></div>;
const User = () => <div><h1>User</h1></div>;
const Error = () => <div><h1>Error</h1></div>

const Frontend = props => {
  console.log('Frontend');
  return (
    <div>
      <h2>Frontend</h2>
      <p><Link to="/">Root</Link></p>
      <p><Link to="/user">User</Link></p>
      <p><Link to="/admin">Backend</Link></p>
      <p><Link to="/the-route-is-swiggity-swoute">Swiggity swooty</Link></p>
      <Switch>
        <Route exact path='/' component={Home}/>
        <Route path='/user' component={User}/>
        <Redirect to={{
          state: { error: true }
        }} />
      </Switch>
      <footer>Bottom</footer>
    </div>
  );
}

const Backend = props => {
  console.log('Backend');
  return (
    <div>
      <h2>Backend</h2>
      <p><Link to="/admin">Root</Link></p>
      <p><Link to="/admin/user">User</Link></p>
      <p><Link to="/">Frontend</Link></p>
      <p><Link to="/admin/the-route-is-swiggity-swoute">Swiggity swooty</Link></p>
      <Switch>
        <Route exact path='/admin' component={Home}/>
        <Route path='/admin/user' component={User}/>
        <Redirect to={{
          state: { error: true }
        }} />
      </Switch>
      <footer>Bottom</footer>
    </div>
  );
}

class GlobalErrorSwitch extends Component {
  previousLocation = this.props.location

  componentWillUpdate(nextProps) {
    const { location } = this.props;

    if (nextProps.history.action !== 'POP'
      && (!location.state || !location.state.error)) {
        this.previousLocation = this.props.location
    };
  }

  render() {
    const { location } = this.props;
    const isError = !!(
      location.state &&
      location.state.error &&
      this.previousLocation !== location // not initial render
    )

    return (
      <div>
        {          
          isError
          ? <Route component={Error} />
          : <Switch location={isError ? this.previousLocation : location}>
              <Route path="/admin" component={Backend} />
              <Route path="/" component={Frontend} />
            </Switch>}
      </div>
    )
  }
}

class App extends Component {
  render() {
    return <Route component={GlobalErrorSwitch} />
  }
}

export default App;
感谢您用最终答案更新您的问题!只是一个建议:也许你可以只保留第 4 个列表和第一个列表,因为其他列表正在使用过时的 api 版本并且分散了答案的注意力
大声笑,我不知道这个日期是什么格式:08.05.2017 如果你不想混淆人们,我建议你使用通用的 ISO8601 日期格式。 08是月还是日? ISO8601 = year.month.day hour.minute.second(逐渐更细化)
很好的更新最终解决方案,但我认为您不需要 previousLocation 逻辑。
完全重写反应路由器的动机是什么。最好是一个很好的理由
这是声明性方法。因此,您可以像使用 React 组件一样设置路由。

K
Karen Liu

在 react-router-v4 中,您不嵌套 <Routes />。相反,您将它们放在另一个 <Component /> 中。

例如

<Route path='/topics' component={Topics}>
  <Route path='/topics/:topicId' component={Topic} />
</Route>

应该成为

<Route path='/topics' component={Topics} />

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <Link to={`${match.url}/exampleTopicId`}>
      Example topic
    </Link>
    <Route path={`${match.path}/:topicId`} component={Topic}/>
  </div>
) 

这是直接来自 react-router documentationbasic example


我可以在基本示例中从您的链接中实现,但是当我手动输入 url 时,它在我的本地主机服务器上不起作用。但它确实在你的例子中。另一方面,当我使用 # 手动键入 url 时,HashRouter 可以正常工作。您是否知道为什么在我的本地主机服务器上,当我手动输入 url 时 BrowserRouter 不起作用?
你能把主题组件变成一个类吗? 'match' 参数是从哪里来的?在渲染()?
似乎很荒谬,您不能只使用 ${match.url} 隐含的 to="exampleTopicId"
您可以为每个文档 reacttraining.com/react-router/web/example/route-config 设置嵌套路由。这将允许根据文档中的主题进行集中路由配置。想想如果无法在更大的项目中管理这将是多么疯狂。
这些不是嵌套路由,它是一个单级路由,仍然使用 Route 的 render 属性,它以功能组件作为输入,仔细看,在 react router < 4 的意义上没有嵌套。RouteWithSubRoutes 是一个-level 使用模式匹配的路由列表。
d
davnicwil

反应路由器 v6

2022 年更新 - v6 包含 Just Work™ 的嵌套 Route 组件。

这个问题是关于 v4/v5 的,但现在最好的答案是尽可能使用 v6!

请参阅 this blog post 中的示例代码。但是,如果您还不能升级...

反应路由器 v4 & v5

确实,为了嵌套 Route,您需要将它们放置在 Route 的子组件中。

但是,如果您喜欢更内联的语法,而不是将您的 Route 拆分为多个组件,您可以为要嵌套在其下的 Route 的 render 属性提供一个功能组件。

<BrowserRouter>

  <Route path="/" component={Frontpage} exact />
  <Route path="/home" component={HomePage} />
  <Route path="/about" component={AboutPage} />

  <Route
    path="/admin"
    render={({ match: { url } }) => (
      <>
        <Route path={`${url}/`} component={Backend} exact />
        <Route path={`${url}/home`} component={Dashboard} />
        <Route path={`${url}/users`} component={UserPage} />
      </>
    )}
  />

</BrowserRouter>

如果您对为什么应该使用 render 属性而不是 component 属性感兴趣,那是因为它会阻止内联功能组件在每次渲染时重新安装。 See the documentation 了解更多详情。

请注意,该示例将嵌套路由包装在 Fragment 中。在 React 16 之前,您可以改用容器 <div>


感谢上帝,唯一一种清晰、可维护且按预期工作的解决方案。我希望反应路由器 3 嵌套路由回来。
这个完美的看起来像有角的路线出口
您应该使用 match.path,而不是 match.url。前者通常用在 Route path 属性中;后者在您推送新路线时(例如 Link to 道具)
以 react-router v4/v5 为例,当有人导航到 /admin 页面时,它会呈现管理页面还是需要导航到 /admin/?谢谢!
我认为嵌套路由的最佳和最简洁的解决方案
t
twharmon

只是想提一下,自从发布/回答了这个问题以来,react-router v4 发生了根本性的变化。

不再有 <Match> 组件! <Switch> 是为了确保只呈现第一个匹配项。 <Redirect> 好 .. 重定向到另一条路线。使用或省略 exact 来输入或排除部分匹配。

请参阅文档。他们都是伟大的。 https://reacttraining.com/react-router/

这是一个例子,我希望可以用来回答你的问题。

<Router>
  <div>
    <Redirect exact from='/' to='/front'/>
    <Route path="/" render={() => {
      return (
        <div>
          <h2>Home menu</h2>
          <Link to="/front">front</Link>
          <Link to="/back">back</Link>
        </div>
      );
    }} />          
    <Route path="/front" render={() => {
      return (
        <div>
        <h2>front menu</h2>
        <Link to="/front/help">help</Link>
        <Link to="/front/about">about</Link>
        </div>
      );
    }} />
    <Route exact path="/front/help" render={() => {
      return <h2>front help</h2>;
    }} />
    <Route exact path="/front/about" render={() => {
      return <h2>front about</h2>;
    }} />
    <Route path="/back" render={() => {
      return (
        <div>
        <h2>back menu</h2>
        <Link to="/back/help">help</Link>
        <Link to="/back/about">about</Link>
        </div>
      );
    }} />
    <Route exact path="/back/help" render={() => {
      return <h2>back help</h2>;
    }} />
    <Route exact path="/back/about" render={() => {
      return <h2>back about</h2>;
    }} />
  </div>
</Router>

希望它有帮助,让我知道。如果这个例子不能很好地回答你的问题,请告诉我,我会看看我是否可以修改它。


Redirect 上没有 exact reacttraining.com/react-router/web/api/Redirect 这将比我正在做的 <Route exact path="/" render={() => <Redirect to="/path" />} /> 干净得多。至少它不会让我使用 TypeScript。
我是否正确理解没有嵌套/子路由之类的东西(不再)?我需要在所有路线中复制基本路线吗? react-router 4 不为以可维护的方式构建路由提供任何帮助吗?
@Ville 我很惊讶;你找到更好的解决方案了吗?我不想到处都有路线,天哪
这将起作用,但请确保您在 webpack 配置中为 bundle.js 将公共路径设置为“/”,否则嵌套路由在页面刷新时不起作用。
a
asukiaaa

我通过用 Switch 包装成功地定义了嵌套路由,并在根路由之前定义了嵌套路由。

<BrowserRouter>
  <Switch>
    <Route path="/staffs/:id/edit" component={StaffEdit} />
    <Route path="/staffs/:id" component={StaffShow} />
    <Route path="/staffs" component={StaffIndex} />
  </Switch>
</BrowserRouter>

参考:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md


重新安排订单解决了我的问题,尽管我不知道这是否会产生任何副作用。但现在工作..谢谢:)
请注意,虽然此解决方案适用于某些情况,但它不适用于您使用嵌套路由呈现分层布局组件的情况,这是您可以在 v3 中使用嵌套路由做的一件好事。
m
mohRamadan

使用钩子

钩子的最新更新是使用 useRouteMatch

主路由组件


export default function NestingExample() {
  return (
    <Router>
      <Switch>
       <Route path="/topics">
         <Topics />
       </Route>
     </Switch>
    </Router>
  );
}

子组件

function Topics() {
  // The `path` lets us build <Route> paths 
  // while the `url` lets us build relative links.

  let { path, url } = useRouteMatch();

  return (
    <div>
      <h2>Topics</h2>
      <h5>
        <Link to={`${url}/otherpath`}>/topics/otherpath/</Link>
      </h5>
      <ul>
        <li>
          <Link to={`${url}/topic1`}>/topics/topic1/</Link>
        </li>
        <li>
          <Link to={`${url}/topic2`}>/topics/topic2</Link>
        </li>
      </ul>

      // You can then use nested routing inside the child itself
      <Switch>
        <Route exact path={path}>
          <h3>Please select a topic.</h3>
        </Route>
        <Route path={`${path}/:topicId`}>
          <Topic />
        </Route>
        <Route path={`${path}/otherpath`>
          <OtherPath/>
        </Route>
      </Switch>
    </div>
  );
}


S
Sanjeev Shakya

像这样的东西。

从“反应”导入反应;从 'react-router-dom' 导入 { BrowserRouter as Router, Route, NavLink, Switch, Link };导入'../assets/styles/App.css'; const Home = () =>

HOME

; const About = () =>

关于

; const Help = () =>

Help

; const AdminHome = () =>

root

; const AdminAbout = () =>

Admin about

; const AdminHelp = () =>

管理员帮助

; const AdminNavLinks = (props) => (

Admin Menu

Admin Home Admin Help 管理员简介 首页 {props.children}
); const NormalNavLinks = (props) => (

普通菜单

主页 帮助 < NavLink to="/about">关于 Admin {props.children}
); const App = () => (
);导出默认应用程序;


D
Devlin Duldulao

React Router v6 或版本 6 的完整答案,以备不时之需。

import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";

/*Routes is used to be Switch*/
const Router = () => {

  return (
    <Routes>
      <Route path="/" element={<LandingPage />} />
      <Route path="games" element={<Games />} />
      <Route path="game-details/:id" element={<GameDetails />} />
      <Route path="dashboard" element={<Dashboard />}>
        <Route path="/" element={<DashboardDefaultContent />} />
        <Route path="inbox" element={<Inbox />} />
        <Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
        <Route path="*" element={<NotFound />} />
      </Route>
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
};
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "@material-ui/core";
import { Outlet } from "react-router";

const Dashboard = () => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      <Outlet />
    </Grid>
  );
};

export default Dashboard;

Github 仓库在这里。 https://github.com/webmasterdevlin/react-router-6-demo


您能否在此处也包括 DashboardSidebarNavigation ?
f
ford04

反应路由器 v6

允许使用嵌套路由(如在 v3 中)和单独的拆分路由(v4、v5)。

嵌套路由

为中小型应用保留所有路线 in one place

<Routes>
  <Route path="/" element={<Home />} >
    <Route path="user" element={<User />} /> 
    <Route path="dash" element={<Dashboard />} /> 
  </Route>
</Routes>

const App = () => { return ( // /js 是堆栈片段的起始路径 } > } /> } /> ); } const Home = () => { const location = useLocation() return (

URL 路径: {location.pathname}

user dashboard

) } const User = () =>
User profile
const Dashboard = () =>
Dashboard
ReactDOM.render(, document.getElementById("root"));

备选方案:通过 useRoutes 将您的路线定义为纯 JavaScript 对象。

单独的路线

您可以使用 separates routes 来满足代码拆分等大型应用的要求:

// inside App.jsx:
<Routes>
  <Route path="/*" element={<Home />} />
</Routes>

// inside Home.jsx:
<Routes>
  <Route path="user" element={<User />} />
  <Route path="dash" element={<Dashboard />} />
</Routes>

const App = () => { return ( // /js 是堆栈片段的起始路径 } /> ); } const Home = () => { const location = useLocation() return (

URL 路径:{location.pathname}

} /> } />

user< /Link> dashboard

) } const User = () =>
用户配置文件
const Dashboard = () => < div>Dashboard
ReactDOM.render(, document.getElementById("root"));


我认为 RoutesRoute 是旧方法,我喜欢这种方法,我在 AngularJS 中也使用了相同的方法,谢谢
A
Aniruddh Agarwal

您可以尝试类似 Routes.js

import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import FrontPage from './FrontPage';
import Dashboard from './Dashboard';
import AboutPage from './AboutPage';
import Backend from './Backend';
import Homepage from './Homepage';
import UserPage from './UserPage';
class Routes extends Component {
    render() {
        return (
            <div>
                <Route exact path="/" component={FrontPage} />
                <Route exact path="/home" component={Homepage} />
                <Route exact path="/about" component={AboutPage} />
                <Route exact path="/admin" component={Backend} />
                <Route exact path="/admin/home" component={Dashboard} />
                <Route exact path="/users" component={UserPage} />    
            </div>
        )
    }
}

export default Routes

应用程序.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Routes from './Routes';

class App extends Component {
  render() {
    return (
      <div className="App">
      <Router>
        <Routes/>
      </Router>
      </div>
    );
  }
}

export default App;

我认为你也可以从这里实现同样的目标。


好点子!在 Java Spring 启动应用程序开发之后开始使用 React 时,我也有同样的想法。我唯一要改变的是Routes.js中的'div'到'Switch'。并且 tbh,您可以在 App.js 中定义所有路由,但将其包装在 index.js 文件中,例如(create-react-app)
是的你是对的!我已经实现了这种方式,这就是我提到这种方法的原因。
D
Devlin Duldulao

React Router v5 的完整答案。


const Router = () => {
  return (
    <Switch>
      <Route path={"/"} component={LandingPage} exact />
      <Route path={"/games"} component={Games} />
      <Route path={"/game-details/:id"} component={GameDetails} />
      <Route
        path={"/dashboard"}
        render={({ match: { path } }) => (
          <Dashboard>
            <Switch>
              <Route
                exact
                path={path + "/"}
                component={DashboardDefaultContent}
              />
              <Route path={`${path}/inbox`} component={Inbox} />
              <Route
                path={`${path}/settings-and-privacy`}
                component={SettingsAndPrivacy}
              />
              <Redirect exact from={path + "/*"} to={path} />
            </Switch>
          </Dashboard>
        )}
      />
      <Route path="/not-found" component={NotFound} />
      <Redirect exact from={"*"} to={"/not-found"} />
    </Switch>
  );
};

export default Router;
const Dashboard = ({ children }) => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      {children}
    </Grid>
  );
};

export default Dashboard;

Github 仓库在这里。 https://github.com/webmasterdevlin/react-router-5-demo


s
seyed mohammad asghari

我更喜欢使用反应功能。该解决方案简短且更具可读性

const MainAppRoutes = () => (
    <Switch>
        <Route exact path='/' component={HomePage} />
        {AdminRoute()}                  
        {SampleRoute("/sample_admin")}  
    </Switch>
);

/*first implementation: without params*/
const AdminRoute = () => ([
    <Route path='/admin/home' component={AdminHome} />,
    <Route path='/admin/about' component={AdminAbout} />
]);

/*second implementation: with params*/
const SampleRoute = (main) => ([
    <Route path={`${main}`} component={MainPage} />,
    <Route path={`${main}/:id`} component={MainPage} />
]); 

s
sampath kumar

**This code worked for me with v6**

index.js

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />}>
          <Route path="login" element={<Login />} />
          <Route path="home" element={<Home />} />
        </Route>
      </Routes>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

应用程序.js:

function App(props) {
  useEffect(() => {
    console.log('reloaded');
// Checking, if Parent component re-rendering or not *it should not be, in the sense of performance*, this code doesn't re-render parent component while loading children
  });
  return (
    <div className="App">
      <Link to="login">Login</Link>
      <Link to="home">Home</Link>
      <Outlet /> // This line is important, otherwise we will be shown with empty component
    </div>
  );
}

登录.js:

const Login = () => {
    return (
        <div>
            Login Component
        </div>
    )
};

主页.js:

const Home= () => {
    return (
        <div>
            Home Component
        </div>
    )
};

E
EVGENY GLUKHOV
interface IDefaultLayoutProps {
    children: React.ReactNode
}

const DefaultLayout: React.SFC<IDefaultLayoutProps> = ({children}) => {
    return (
        <div className="DefaultLayout">
            {children}
        </div>
    );
}


const LayoutRoute: React.SFC<IDefaultLayoutRouteProps & RouteProps> = ({component: Component, layout: Layout, ...rest}) => {
const handleRender = (matchProps: RouteComponentProps<{}, StaticContext>) => (
        <Layout>
            <Component {...matchProps} />
        </Layout>
    );

    return (
        <Route {...rest} render={handleRender}/>
    );
}

const ScreenRouter = () => (
    <BrowserRouter>
        <div>
            <Link to="/">Home</Link>
            <Link to="/counter">Counter</Link>
            <Switch>
                <LayoutRoute path="/" exact={true} layout={DefaultLayout} component={HomeScreen} />
                <LayoutRoute path="/counter" layout={DashboardLayout} component={CounterScreen} />
            </Switch>
        </div>
    </BrowserRouter>
);