【问题标题】:How to get routes from other location/function in react-router-dom v6?如何从 react-router-dom v6 中的其他位置/功能获取路由?
【发布时间】:2022-01-02 10:07:12
【问题描述】:

我正在尝试 React Router V06,但遇到了一个问题,我一直在以这种方式尝试,但每个路由和页面都是空白的。

代码:

// Main App Function
    const App = () => {
      return (
        <Router>
          <Fragment>
            <Navbar />
            <Routes>
              <Route index strict path="/" element={<Landing />} />
      **{/* Here I want to render paths from other function*/}**
              <Route element={<AppRoutes />} />
            </Routes>
          </Fragment>
        </Router>
      );
    };
    
    export default App;
    
    // In AppRoutes Function
    const AppRoutes = () => (
      <section className="container">
        <Routes>
          <Route strict path="login" element={<Login />} />
          <Route strict path="register" element={<Register />} />
          <Route path="*" element={<NotFound />} />
        </Routes>
      </section>
    );
    
    export default AppRoutes;

【问题讨论】:

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


    【解决方案1】:

    在应用程序中,将Landing组件声明为索引页面,并在“/*”路径上渲染AppRoutes以允许匹配子路由。

    应用程序

    <Router>
      <Navbar />
      <Routes>
        <Route index element={<Landing />} />
        <Route path="/*" element={<AppRoutes />} />
      </Routes>
    </Router>
    

    AppRoutes

    const AppRoutes = () => (
      <section className="container">
        <Routes>
          <Route path="login" element={<Login />} />
          <Route path="register" element={<Register />} />
          <Route path="*" element={<NotFound />} />
        </Routes>
      </section>
    );
    

    【讨论】:

    • 谢谢,我真傻,我想不出这个小问题。效果很好!
    • @Gazi 不用担心,有时会发生在我们身上。不要忘记someone answers时要做什么。干杯!
    猜你喜欢
    • 2022-06-23
    • 2021-11-03
    • 2022-07-09
    • 2022-08-02
    • 2022-01-09
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2022-03-23
    相关资源
    最近更新 更多