React Router 6 alpha 4嵌套路由

提供以下沙箱,不确定要了解如何呈现Bb组件

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

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="a" element={<Aa />}>
          <Route path="b" element={<Bb />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

function Aa() {
  return (
    <p>
      Hello
    </p>
  );
}

function Bb() {
  return <p>World</p>;
}

https://codesandbox.io/s/still-shadow-337zc?file=/src/App.js

浏览到/ a / b仅呈现Aa组件

评论
EVE
EVE

react-router v6 exposes an Outlet element that you must use inside your parent Route so that any nested children can be rendered by react-router-dom isnide of it

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

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="a" element={<Aa />}>
          <Route path="b" element={<Bb />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

function Aa() {
  return <p>Hello <Outlet /></p>;
}

function Bb() {
  return <p>World</p>;
}

Working demo

If you want only Bb to render at a/b you define it as a separate route like

<BrowserRouter>
  <Routes>
    <Route path="a" element={<Aa />}/>
    <Route path="a/b" element={<Bb />} />
  </Routes>
</BrowserRouter>
点赞
评论
Lynch
Lynch

@Shubham Khatri的答案的其他说明:

<Route path="a" element={<Aa />}>
    <Route path="b" element={<Bb />} />
</Route>

/a/b/ will render

<Aa>
  <Bb />
</Aa>

If you want to display only Bb component, nested route is not the right way.

点赞
评论