React router v6 嵌套路由不显示子元素

Jum*_*ail 1 reactjs react-router-dom

return (
<BrowserRouter>
  <Routes>
    <Route path="/parent" element={<h1>I am parent</h1>}>
      <Route path="child" element={<h1>I am child</h1>} />
    </Route>
    <Route
      path="*"
      element={
        <main style={{ padding: '1rem' }}>
          <p>There's nothing here!</p>
        </main>
      }
    />
  </Routes>
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)

当我访问路线 http://localhost:3000/parent/child 时,我期待以下输出。

我是父母我是孩子

但我得到了输出

我是家长

"dependencies": {
    "@craco/craco": "^6.4.0",
    "@heroicons/react": "^1.0.5",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/jest": "^26.0.15",
    "@types/node": "^12.0.0",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "axios": "^0.24.0",
    "js-cookie": "^3.0.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-hook-form": "^7.19.4",
    "react-router-dom": "6",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1",
    "zustand": "^3.6.5"
},
Run Code Online (Sandbox Code Playgroud)

Sté*_*ret 11

React v6 需要知道您希望子元素在父元素中的确切位置显示。为此,您需要添加一个<Outlet />组件。

请参阅https://reactrouter.com/docs/en/v6/examples/basic

所以你的例子应该写成:

return (
<BrowserRouter>
  <Routes>
    <Route path="/parent" element={<><h1>I am parent</h1><Outlet /></>}>
      <Route path="child" element={<h1>I am child</h1>} />
    </Route>
    <Route
      path="*"
      element={
        <main style={{ padding: '1rem' }}>
          <p>There's nothing here!</p>
        </main>
      }
    />
  </Routes>
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)