簡體   English   中英

在另一個組件中定義 React Router 路由

[英]Define React Router Routes In Another Components

我正在使用 react-router-dom 5.2.0。 我想要 2 個定義我所有路線的文件。 1 個文件用於公共路線,1 個文件用於私人路線。 當我點擊 home 路由而不是 /content 路由時,正確的組件呈現。

App.jsx 返回:

<BrowserRouter>
  <Switch>
    <PublicRoutes />
    <PrivateRoutes />
  </Switch>
</BrowserRouter>

PublicRoutes.jsx 返回:

<Route path="/" exact render={() => <h1>home route</h1>} />

PrivateRoutes.jsx 返回:

<Route path="/content" exact render={() => <h1>Content Route</h1>} />

我可以使用“home route”加載 /,但是當我點擊 /content url 時沒有任何渲染。

這些開關需要 go您的包裝路線內,如下所示:

import { BrowserRouter, Switch, Route } from "react-router-dom";
import "./styles.css";

const PublicRoutes = () => (
  <Switch>
    <Route path="/" exact render={() => <h1>home route</h1>} />
  </Switch>
);
const PrivateRoutes = () => (
  <Switch>
    <Route path="/content" exact>
      <h1>Content Route</h1>
    </Route>
  </Switch>
);

export default function App() {
  return (
    <BrowserRouter>
      <PublicRoutes />
      <PrivateRoutes />
    </BrowserRouter>
  );
}

https://codesandbox.io/s/shy-river-ysv4w?file=/src/App.js

問題

Switch組件返回並呈現第一個匹配的RouteRedirect組件。 PublicRoutesPrivateRoutes都不是, PublicRoutes默認返回。

轉變

渲染與位置匹配的第一個子<Route><Redirect>

解決方案

您需要在Switch中渲染一個Route來檢查身份驗證條件並有條件地渲染一個或另一個。

<BrowserRouter>
  <Switch>
    <Route
      render={(routeProps) => authCondition ? (
        <PublicRoutes {...routeProps} />
      ) : (
        <PrivateRoutes {...routeProps} />
      )}
    />
  </Switch>
</BrowserRouter>

如果您的公共和私有路由在路徑上被分割,那么您可能更簡單地在它們的透視路徑上渲染每個。

<BrowserRouter>
  <Switch>
    <Route path="/content" component={PrivateRoutes} />
    <Route path="/" component={PublicRoutes} />
  </Switch>
</BrowserRouter>

如果您有進一步的嵌套路由,那么您可能需要渲染一個基於每個基本路徑的嵌套Switch

在 react router v6 中,可以使用outlet base on docs

或者你應該使用這個

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="dashboard/*" element={<Dashboard />} />
    </Routes>
  );
}

function Dashboard() {
  return (
    <div>
      <p>Look, more routes!</p>
      <Routes>
        <Route path="/" element={<DashboardGraphs />} />
        <Route path="invoices" element={<InvoiceList />} />
      </Routes>
    </div>
  );
}

請注意 * end of path="dashboard/*"

暫無
暫無

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

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