簡體   English   中英

如何使用react-router導航具有多個頁面的組件

[英]How to use react-router to navigate component with multiple pages

假設我有2頁和幾個組件。 第一頁是登錄頁面,另一頁是主菜單。 登錄頁面僅包含1個組件。 用戶登錄到網站后,我希望react-router導航到主菜單,該主菜單下方即具有導航欄和一些組件。 我希望它能夠導航到每個組件並將導航欄始終保持在頂部,即使URL已更改。

這是我嘗試過的代碼

// Inside the root component
<BrowserRouter>
     <Route path="/menu" component={MenuForm}/>
     <Route path="/login" component={LoginForm}/>
</BrowserRouter>

//Inside the menu page component  
<Navbar/>
<Route path="/shop" component={Shop}/>
<Route path="/categories" component={Categories}/>

使用此代碼,我只能導航至菜單頁面和登錄頁面,但無法導航至作為主菜單的子組件的商店和類別

您需要主頁

<Route path="/home" component={Home}/> // all your menu and everything here

現在,如果您想在家中進入菜單,您可以像這樣

<Route path="/home/menu" component={Menu}/>

此組件將在您設置嵌套路線的主頁中呈現,因此匹配的路線組件將呈現

<Route path="/home/menu" component={menu}/>
<Route path="/home/profile" component={Profile}/>

我想您應該考慮創建容器組件。 第一個容器將包含您的登錄路由,即“身份驗證容器”,其他組件應包含在應用程序路由中,即“應用程序容器”。 您可以擁有自己的包裝器。

const AppRoutes = () => {
    return (
        <>
            <Navigation scrolling={scrolling} />
            <Switch>
                <ProtectedRoute exact path="/profile" component={UserProfile} />
                <ProtectedRoute exact path="/my-orders" component={MyOrders} />
                <ProtectedRoute path="/my-saved-result" component={SavedResults} />
            </Switch>
        </>
    )
}

如果您使用react-router v4 ,則可以通過Switch組件以聲明方式定義路由,如下所示:

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

const MenuForm = () => (
  <div className="app-routes">
    <NavBar />
    <Switch>
    <Route exact path="/menu">
      <Redirect to="/menu/shop" />
      </Route>
      <Route path="/menu/shop" component={Shop} />
      <Route path="/menu/categories" component={Categories} />
    </Switch>
  </div>
);

我正在這樣使用

    <div className="main-panel">
        <Navbar />
        <div className="content" style={{ backgroundColor: '#f4f3ef' }}>
            <Switch>
                <Route path="/" exact component={Home} />
                <Route path="/reports" component={ReportMain} />
                <Route path="/showWebService" component={ShowWebService} />
            </Switch>
        </div>         
    </div>

導航欄鏈接到導航欄時,它是靜態的,僅使這些組件呈現。

<Link to="/reports">
  <p>Reports</p>
</Link>

使用鏈接調用組件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM